Log 1 建立本身的gemvim
背景:好奇gem包的用法,首先搞清楚什麼是gem包。那咱們就先來建立一個本身的gem包。ruby
時間:2014-3-8測試
環境:Ubuntu + Ruby 1.9.3ui
記錄:Royspa
建立目錄結構code
$ cd ~;mkdir -p codes/ruby/sayhello $ cd codes/ruby/sayhello $ mkdir bin $ mkdir lib
建立vim lib/sayhello.rbblog
1 #!/usr/bin/ruby 2 3 def sayhello(name) 4 puts "#{name} says hello to you!" 5 end
建立vim bin/sayhelloip
1 #!/usr/bin/ruby 2 require 'sayhello' 3 param_num = 0 4 while param_num < ARGV.length 5 sayhello(ARGV[param_num]) 6 param_num += 1 7 end
建立vim sayhello.specci
1 SPEC=Gem::Specification.new do |s| 2 s.name = 'sayhello' 3 s.version = '0.1.0' 4 s.files = 'lib/sayhello.rb' 5 s.executable = 'sayhello' 6 s.summary = 'This is an example!' 7 s.description = 'A sample to say hello.' 8 s.email = 'burningroy2011@gmail.com' 9 s.homepage = "<link>" 10 s.authors = ['Roy'] 11 end
sayhello目錄結構io
$ tree . . | |-----bin | |---sayhello |-----lib | |---sayhello.rb |-----sayhello.spec
執行build
$ gem build sayhello.spec
安裝sayhello包
$ gem install sayhello-0.1.0.gem Successfully installed sayhello-0.1.0 1 gem installed Installing ri documentation for sayhello-0.1.0... Installing RDoc documentation for sayhello-0.1.0...
已經安裝的gem位置
$ cd /var/lib/gems/1.9.1/gems $ tree . .----sayhello-0.1.0 | |-----bin | |---sayhello |-----lib |---sayhello.rb
使用包進行測試
建立vim ~/dash.rb
1 #!/usr/bin/ruby 2 3 require 'rubygems' 4 load Gem.bin_path('sayhello','sayhello')
執行~/dash.rb(注意打開執行權限)
$ ~/dash.rb Roy Lydia Osan Roy says hello to you! Lydia says hello to you! Osan says hello to you!
在dash.rb中,咱們經過load Gem.bin_path。去調用sayhello包中的bin/sayhello,而且bin/sayhello調用了lib/sayhello.rb。