Rails アプリから汎用的な機能を gem 化する方法

これから Rails 用の gem を作ってみたい人向けの内容。

gem 化する

実は下記のようなコードを置くだけで RubyGems に登録しなくても、 gem として認識される。

Gemfile

gem 'hello_world', path: 'lib/hello_world'

lib/hello_world/hello_world.gemspec

# coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)

Gem::Specification.new do |spec|
  spec.name          = 'hello_world'
  spec.version       = '0.0.1'
  spec.summary       = ''
  spec.authors       = ['']
end

lib/hello_world/lib/hello_world.rb

module HelloWorld
  def self.say
    puts 'Hello, World'
  end
end

これは簡単な例だけど、 rails c で読み込まれていることが確認できる。

HelloWorld.say
#=> "Hello, World"

仕事のコードで「これ gem にできるかも?!」みたいなのを gem 化して、ある程度試して安定してきたら公開すると良い。

一般公開する

概要は下記のような感じ。分からんところはググれば参考になる記事がたくさん見つかると思います。

$ bundle gem hello_world 
MIT License enabled in config
Code of conduct enabled in config
      create  hello_world/Gemfile
      create  hello_world/.gitignore
      create  hello_world/lib/hello_world.rb
      create  hello_world/lib/hello_world/version.rb
      create  hello_world/hello_world.gemspec
      create  hello_world/Rakefile
      create  hello_world/README.md
      create  hello_world/bin/console
      create  hello_world/bin/setup
      create  hello_world/.travis.yml
      create  hello_world/.rspec
      create  hello_world/spec/spec_helper.rb
      create  hello_world/spec/hello_world_spec.rb
      create  hello_world/LICENSE.txt
      create  hello_world/CODE_OF_CONDUCT.md
$ cd hello_world/
$ vim hello_world.gemspec # TODO: を直す
$ vim README.md # 使い方を書く
$ bundle exec rake release # RubyGems に公開される