gem を作ってみる#1

About Dr Nic Williams

newgem を使った作法を学びます.

必要パッケージのインストール

% sudo gem install rubigen
% sudo gem install newgem

テンプレートの作成

% newgem map_by_method

モジュールの作成

これから作るのは MapByMethod モジュールなので,lib/map_by_method.rb が最初に呼び出されます.

  • lib/map_by_method.rb
module MapByMethod
  VERSION = "0.0.1"

  def self.included(base)
    super

    base.module_eval <<-EOS
      def method_missing(method, *arg, &block)
        super
      rescue NoMethodError
        error = $!
        begin
          re = /(map|collect|select|each|reject)_([\\w\\_]+\\??)/
          if (match = method.to_s.match(re))
            iterator, callmethod = match[1..2]
            return self.send(iterator){|item| item.send callmethod}
          end
          return self.map{|item| item.send method.to_s.singularize.to_sym}
        rescue NoMethodError
          nil
        end
      end
    EOS
  end
end

unless String.instance_methods.include? "singularize"
  class String
    def singularize
      self.gsub(/e?s\Z/, '')
    end
  end
end

Array.send :include, MapByMethod

動作確認

一応動くことを確認してみる.

% irb
>> require 'lib/map_by_method'
=> true
>> a = (1..10).to_a
=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>> a.map_to_s
=> ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"]

パッケージ作成

rake package コマンドで作成します.

% rake package

パッケージファイルは pkg 配下に作成されます.

% ls pkg/
map_by_method-0.0.1  map_by_method-0.0.1.gem  map_by_method-0.0.1.tgz

インストール・実行・アンインストール

% sudo gem install pkg/map_by_method-0.0.1.gem
% irb
>> require 'map_by_method'
=> true
>> a = (1..10).to_a
=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>> a.map_to_s
=> ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"]
% ls /usr/lib/ruby/gems/1.8/gems/map_by_method-0.0.1
History.txt  Manifest.txt  PostInstall.txt  README.rdoc  Rakefile  lib  script  test
% sudo gem uninstall map_by_method
Successfully uninstalled map_by_method-0.0.1
% ls /usr/lib/ruby/gems/1.8/gems/map_by_method-0.0.1
ls: cannot access /usr/lib/ruby/gems/1.8/gems/map_by_method-0.0.1: No such file or directory