Ruby中的gem包管理的使用及gem源搭建教程

2019-09-25 09:37:57于海丽

编译后可以查看文件夹结构 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'