Ruby中的gem包管理的使用及gem源搭建教程
熟练使用RubyGems ###常见指令
另外,在安装插件时,系统会默认安装该插件的RDoc和ri文件,如果不希望安装这些该件,可在安装时使用--no-ri --no-rdoc参数: gem install gem_name --no-ri --no-rdoc 也可以在用户目录~下,新建一个.gemrc文档,内容如下:
gem: --no-ri --no-rdoc 系统将默认不安装RDoc和ri文件。 ###国内RubyGems镜像 如果服务器在国内,安装所需的gems将是异常痛苦的体验,所幸的是,现在可以使用淘宝的镜像: $ gem sources --remove https://rubygems.org/ $ gem sources -a http://ruby.taobao.org/ $ gem sources -l 如果显示: *** CURRENT SOURCES *** http://ruby.taobao.org 就说明更改成功啦,你现在可以从国内镜像安装rugy gems啦。详细内容可参考 Rubygems镜像 如果使用Bundler管理Ruby Gems,可以修改Gemfile: source 'http://ruby.taobao.org/' gem 'rails','3.2.2' ... ... ... ###建立和分享Ruby Gems 根据官方的简介: gem update --system #Update to the latest RubyGems version gem build foo.gemspec #Build your gem gem push foo-1.0.0.gem #Deploy your gem instantly 如何建立自己的Rubygems 以创建topico-0.0.1.gem为例: ####建立文件夹 . ├── lib │ └── topico.rb └── topico.gemspec 注意:lib目录下必须有个和你gem名字一样的rb文件。 ####编写代码 libtopico.rb class Topico def self.hello puts "Hello,RubyGems!" end end ####编辑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 = 'username@username.com' s.files = ["lib/topico.rb"] s.homepage = 'http://rubygems.org/gems/topico' end 这里仅列出了较为常见的属性。 ####编译生成gem $ gem build topico.gemspec 系统会提示信息:
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 系统会提示: Successfully installed topico-0.0.1 1 gem installed Installing ri documentation for topico-0.0.1... Installing RDoc documentation for topico-0.0.1... 在irb中测试使用 irb: irb(main):001:0> require 'topico' => true irb(main):002:0> Topico.hello Hello,RubyGems! => nil ####发布到RugyGems网站 先设置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 设置成功后发布: $ gem push topico-0.0.1.gem Pushing gem to https://rubygems.org... Successfully registered gem: topico (0.0.1) 发布成功,这样大家都可以使用你的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中包含可执行该件 (1)在插件目录下,建立bin文件夹: 生成可执行该件,并且将权限修改为可运行。 $ mkdir bin $ touch bin/greeting $ chmod a+x bin/greeting (2)修改可执行文件内容 #!/usr/bin/env ruby require 'topico' puts Topico.hello (3)修改GemSpec,添加一行s.executables s.executables << 'greeting' (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |