編寫(xiě)一個(gè)最簡(jiǎn)單的例子
1. 建好如下文件夾
注意:lib目錄下必須有個(gè)和你gem名字一樣的rb文件。
- $ cd hola
- $ tree
- .
- ├── hola.gemspec
- └── lib
- └── hola.rb
2. 編寫(xiě)代碼
. hola.rb
- % cat lib/hola.rb
- class Hola
- def self.hi
- puts "Hello world!"
- end
- end
.hola.gemspec
- % cat hola.gemspec
- Gem::Specification.new do |s|
- s.name = 'hola'
- s.version = '0.0.0'
- s.date = '2010-04-28'
- s.summary = "Hola!"
- s.description = "A simple hello world gem"
- s.authors = ["Nick Quaranto"]
- s.email = 'nick@quaran.to'
- s.files = ["lib/hola.rb"]
- s.homepage =
- 'http:///gems/hola'
- end
這里面可以設(shè)置很多屬性。我會(huì)專門(mén)寫(xiě)篇文章介紹。
上面字段的意思,比較簡(jiǎn)單。相信大家都能理解。
3.編譯生成gem
- % gem build hola.gemspec
- Successfully built RubyGem
- Name: hola
- Version: 0.0.0
- File: hola-0.0.0.gem
-
- % gem install ./hola-0.0.0.gem
- Successfully installed hola-0.0.0
- 1 gem installed
4.測(cè)試使用
- % irb
- >> require 'hola'
- => true
- >> Hola.hi
- Hello world!
注意:在ruby 1.9.2之前到版本里面,需要先require 'rubygem',才能使用我們寫(xiě)的gem.
5.發(fā)布到rubygems網(wǎng)站
- $ curl -u tom https:///api/v1/api_key.yaml >
- ~/.gem/credentials
- Enter host password for user 'tom':
設(shè)定完之后發(fā)布
- % gem push hola-0.0.0.gem
- Pushing gem to RubyGems.org...
- Successfully registered gem: hola (0.0.0)
發(fā)布成功。
這樣任何一個(gè)人都可以使用你寫(xiě)的gem了。
稍微復(fù)雜的rubygem例子
上面的例子只有一個(gè)ruby文件,一般gem應(yīng)該沒(méi)有這么簡(jiǎn)單的。
下面說(shuō)下有多個(gè)ruby文件該怎么寫(xiě)。
1. 目錄結(jié)構(gòu)
多了個(gè)hola目錄和translator.rb文件
- % tree
- .
- ├── hola.gemspec
- └── lib
- ├── hola
- │ └── translator.rb
- └── hola.rb
2. 代碼
lib/hola/translator.rb
- % cat lib/hola/translator.rb
- class Hola::Translator
- def initialize(language)
- @language = language
- end
-
- def hi
- case @language
- when :spanish
- "hola mundo"
- else
- "hello world"
- end
- end
- end
lib/hola.rb
- % cat lib/hola.rb
- class Hola
- def self.hi(language = :english)
- translator = Translator.new(language)
- translator.hi
- end
- end
-
- require 'hola/translator'
.hola.gemspec
- % cat hola.gemspec
- Gem::Specification.new do |s|
- s.name = 'hola'
- s.version = '0.0.0'
- s.date = '2010-04-28'
- s.summary = "Hola!"
- s.description = "A simple hello world gem"
- s.authors = ["Nick Quaranto"]
- s.email = 'nick@quaran.to'
- s.files = ["lib/hola.rb", "lib/hola/translator.rb"]
- s.homepage =
- 'http:///gems/hola'
- end
紅色是和上面不一樣的地方。
其他步驟和上面一樣了。很簡(jiǎn)單吧!
最后說(shuō)下怎么寫(xiě)個(gè) gem包含可執(zhí)行文件的例子。
這個(gè)也很簡(jiǎn)單。像rake就是典型的包含可執(zhí)行文件的gem.
1. 在剛才工程目錄下建個(gè)bin文件夾
生成可執(zhí)行文件,并且修改權(quán)限為可運(yùn)行。
- % mkdir bin
- % touch bin/hola
- % chmod a+x bin/hola
2. 修改可執(zhí)行文件內(nèi)容 bin/hola
- #!/usr/bin/env ruby
-
- require 'hola'
- puts Hola.hi(ARGV[0])
測(cè)試下
- % ruby -Ilib ./bin/hola
- hello world
-
- % ruby -Ilib ./bin/hola spanish
- hola mundo
3 .最后修改gemspec
- % head -4 hola.gemspec
- Gem::Specification.new do |s|
- s.name = 'hola'
- s.version = '0.0.1'
- s.executables << 'hola'
其他就和上面一樣了。很簡(jiǎn)單吧。
|