LoginSignup
2
2

More than 5 years have passed since last update.

Rails4でGemを作る練習をしてみた。

Last updated at Posted at 2014-01-04

Rails GuideのPluginの作り方に沿ってお試しでGemを作成して自分のGitHubにPushしてみました。

Gemfile
 gem 'yaffle', git: 'https://github.com/makoto0306/rails_gem_lerning'

とGemfileに書いてbundleすることができます。

Guideの通りにやってみたんですが、次の2箇所を変えないとうまく動きませんでした。

・テストの親クラスがTest::Unit::TestCaseになっているけど動かなかったので
 ActiveSupport::TestCaseにしました。

・作り終えてGitHubにPushしてbundleすると下記のエラーが出たのでRails_ROOT 直下のyaffle.gemspecファイルのTODOと書いてあるところ(名前やemailなど)を書き換えるとうまくいきました。
erb:エラー
yaffle at /{自分のディレクトリ}/rails_gem_lerning-a93d479cfe0a did not have a valid gemspec.
This prevents bundler from installing bins or native extensions, but that may not affect its functionality.
The validation message from Rubygems was: "nothing" is not a URI

以下に簡単な手順を記します。

  1. rails plugin new {プロジェクト名}でプロジェクトを作成
  2. 既存のクラスなどを拡張する場合はlib/プロジェクト名/core_ext.rbに
  3. テスト用プロジェクトはtest/dummyにあるのでそこで試す
  4. ActiveRecordの拡張メソッドは下記のように書く

プロジェクト名Yaffle

yaffle/lib/yaffle/acts_as_yaffle.rb

module Yaffle
  module ActsAsYaffle
   extend ActiveSupport::Concern

    module ClassMethods   #クラスメソッド
      def acts_as_yaffle(options = {})
        cattr_accessor :yaffle_text_field
        self.yaffle_text_field = (options[:yaffle_text_field] || :last_squawk).to_s
      end
          #スコープがローカルインスタンスなのでacts_as_yaffleメソッドが
          #使用された場合のみインスタンスメソッドも使用可能となる。
      include Yaffle::ActsAsYaffle::LocalInstanceMethods  
    end

   module LocalInstanceMethods  #インスタンスメソッド
      def squawk(string)
        write_attribute(self.class.yaffle_text_field, string.to_squawk)
      end
    end
  end

end
#ActiveRecord:Baseのincludeメソッドを呼び出す(引数はYaffle::ActsAsYaffleつまり上のモジュール)
ActiveRecord::Base.send :include, Yaffle::ActsAsYaffle 

次はこのあたりを読んでオリジナルのGemをRubyGemsで公開できればいいなーと思います。

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2