熟練使用RubyGems
RubyGems是Ruby的插件管理系統(tǒng),可以輕松安裝及管理Ruby函式庫。可以在RubyGems上找到所有開源套件。
###常見指令
另外,在安裝插件時,系統(tǒng)會默認安裝該插件的RDoc和ri文件,如果不希望安裝這些該件,可在安裝時使用--no-ri --no-rdoc參數(shù):
gem install gem_name --no-ri --no-rdoc
gem: --no-ri --no-rdoc
系統(tǒng)將默認不安裝RDoc和ri文件。
###國內(nèi)RubyGems鏡像
如果服務器在國內(nèi),安裝所需的gems將是異常痛苦的體驗,所幸的是,現(xiàn)在可以使用淘寶的鏡像:
$ gem sources --remove https://rubygems.org/$ gem sources -a http://ruby.taobao.org/$ gem sources -l
如果顯示:
*** CURRENT SOURCES ***http://ruby.taobao.org
就說明更改成功啦,你現(xiàn)在可以從國內(nèi)鏡像安裝rugy gems啦。詳細內(nèi)容可參考 Rubygems鏡像
如果使用Bundler管理Ruby Gems,可以修改Gemfile:
source 'http://ruby.taobao.org/'gem 'rails', '3.2.2'... ... ...
###建立和分享Ruby Gems
根據(jù)官方的簡介:
gem update --system #Update to the latest RubyGems versiongem build foo.gemspec #Build your gemgem push foo-1.0.0.gem #Deploy your gem instantly
如何建立自己的Rubygems
###簡單的示例:
以創(chuàng)建topico-0.0.1.gem為例:
####建立文件夾
.├── lib│ └── topico.rb└── topico.gemspec
注意:lib目錄下必須有個和你gem名字一樣的rb文件。
####編寫代碼 lib/topico.rb
class Topico def self.hello puts "Hello, RubyGems!" endend
####編輯GemSpec文件 topico.gemspec
Gem::Specification.new do |s| s.name = 'topico' s.version = '0.0.1' s.date = '2012-03-11' s.summary = 'Greeting from Topico' s.description = 'Topico shows a greeting to RubyGems' s.authors = 'Author Name' s.email = '[email protected]' s.files = ["lib/topico.rb"] s.homepage = 'http://rubygems.org/gems/topico'end
這里僅列出了較為常見的屬性。
####編譯生成gem
$ gem build topico.gemspec
系統(tǒng)會提示信息:
Successfully built RubyGem Name: topico Version: 0.0.1 File: topico-0.0.1.gem
編譯后可以查看文件夾結構 tree
.├── lib│ └── topico.rb├── topico-0.0.1.gem└── topico.gemspec
注意新生成的topico-0.0.1.gem
####安裝并測試gem
安裝topico-0.0.1.gem
$ gem install ./topico-0.0.1.gem
系統(tǒng)會提示:
Successfully installed topico-0.0.11 gem installedInstalling ri documentation for topico-0.0.1...Installing RDoc documentation for topico-0.0.1...
在irb中測試使用 irb:
irb(main):001:0> require 'topico'=> trueirb(main):002:0> Topico.helloHello, RubyGems!=> nil
####發(fā)布到RugyGems網(wǎng)站
先設置RubyGems的用戶名和密碼:
$ curl -u username https://rubygems.org/api/v1/api_key.yaml > ~/.gem/credentials
Enter host password for user 'username': % Total % Received % Xferd Average Speed Time Time Time Current Dload Upload Total Spent Left Speed 0 56 0 56 0 0 25 0 --:--:-- 0:00:02 --:--:-- 144
設置成功后發(fā)布:
$ gem push topico-0.0.1.gem
Pushing gem to https://rubygems.org...Successfully registered gem: topico (0.0.1)
發(fā)布成功,這樣大家都可以使用你的Rubygem啦。
###稍微復雜一些的示例:
下面看一下如何組織多個ruby文件。
1.目錄結構
.├── lib│ ├── ext│ │ └── calculation.rb│ └── topico.rb└── topico.gemspec
2.編寫GemSpec
在s.files一行,修改:
s.files = ["lib/topico.rb", "lib/ext/calculation.rb"]
重新gem build即可。
3.如何在Gem中包含可執(zhí)行該件
(1)在插件目錄下,建立bin文件夾:
生成可執(zhí)行該件,并且將權限修改為可運行。
$ mkdir bin$ touch bin/greeting$ chmod a+x bin/greeting
(2)修改可執(zhí)行文件內(nèi)容
#!/usr/bin/env rubyrequire 'topico'puts Topico.hello
(3)修改GemSpec,添加一行s.executables
s.executables << 'greeting'
新聞熱點
疑難解答
圖片精選