建立一个rubygem ( how to create a ruby gem)

访问量: 2161

参考:  http://guides.rubygems.org/make-your-own-gem

1. 假设你的gem名字是 "hola", 就要先建立这样的目录结构。(记得 lib下要有个跟项目同名的rb文件哦)

% tree
.
├── hola.gemspec
└── lib
    └── hola.rb

2. 编辑 lib/hola.rb 这个文件,让它看起来如下:

class Hola
  def self.hi
    puts "Hello world!"
  end
end

3. 编辑 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://rubygems.org/gems/hola'
end

4. 建立这个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

5. 试试这个gem ...

% irb
>> require 'hola'
=> true
>> Hola.hi
Hello world!

6. 在 rubygems.org 上注册并且登录,进入到profile 界面,就会发现

API Access
Your API key is 6cd7fafaeb3b7f721da09686f9668???.
If you want to use gem commands from the command line, you'll need a ~/.gem/credentials file, which you can generate using the following command:
$ curl -u Siwei Shen https://rubygems.org/api/v1/api_key.yaml > ~/.gem/credentials

7. push this gem to rubygems.org

% gem push hola-0.0.0.gem
Pushing gem to RubyGems.org...
Successfully registered gem: hola (0.0.0)

8 . 来个稍微复杂点儿的文件结构:

.
├── hola.gemspec
└── lib
    ├── hola
    │   └── translator.rb
    └── hola.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

% cat lib/hola.rb
class Hola
  def self.hi(language = :english)
    translator = Translator.new(language)
    translator.hi
  end
end

require 'hola/translator'

然后在irb中试一下:

% irb -Ilib -rhola
irb(main):001:0> Hola.hi(:english)
=> "hello world"
irb(main):002:0> Hola.hi(:spanish)
=> "hola mundo"

订阅/RSS Feed

Subscribe

分类/category