Ruby

来源:互联网 时间:1970-01-01

Log 1 创建自己的gem

背景:好奇gem包的用法,首先搞清楚什么是gem包。那我们就先来创建一个自己的gem包。

时间:2014-3-8

环境:Ubuntu + Ruby 1.9.3

记录:Roy


 

 

创建目录结构

$ cd ~;mkdir -p codes/ruby/sayhello

$ cd codes/ruby/sayhello

$ mkdir bin

$ mkdir lib

创建vim lib/sayhello.rb

1 #!/usr/bin/ruby

2

3 def sayhello(name)

4 puts "#{name} says hello to you!"

5 end

创建vim bin/sayhello

1 #!/usr/bin/ruby

2 require 'sayhello'

3 param_num = 0

4 while param_num < ARGV.length

5 sayhello(ARGV[param_num])

6 param_num += 1

7 end

创建vim sayhello.spec

 1 SPEC=Gem::Specification.new do |s|

2 s.name = 'sayhello'

3 s.version = '0.1.0'

4 s.files = 'lib/sayhello.rb'

5 s.executable = 'sayhello'

6 s.summary = 'This is an example!'

7 s.description = 'A sample to say hello.'

8 s.email = '[email protected]'

9 s.homepage = "<link>"

10 s.authors = ['Roy']

11 end

sayhello目录结构

$ tree .

.

|

|-----bin

| |---sayhello

|-----lib

| |---sayhello.rb

|-----sayhello.spec

执行build

$ gem build sayhello.spec

安装sayhello包

$ gem install sayhello-0.1.0.gem

Successfully installed sayhello-0.1.0

1 gem installed

Installing ri documentation for sayhello-0.1.0...

Installing RDoc documentation for sayhello-0.1.0...

已经安装的gem位置

$ cd /var/lib/gems/1.9.1/gems

$ tree .

.----sayhello-0.1.0

|

|-----bin

| |---sayhello

|-----lib

|---sayhello.rb

使用包进行测试

创建vim ~/dash.rb

1 #!/usr/bin/ruby

2

3 require 'rubygems'

4 load Gem.bin_path('sayhello','sayhello')

执行~/dash.rb(注意打开执行权限)

$ ~/dash.rb Roy Lydia Osan

Roy says hello to you!

Lydia says hello to you!

Osan says hello to you!

在dash.rb中,我们通过load Gem.bin_path。去调用sayhello包中的bin/sayhello,并且bin/sayhello调用了lib/sayhello.rb。

 

 

 

 


相关阅读:
Top