簡単なプラグインの作り方(HowToWriteAnActsAsFoxPlugin)

【ma2注】Rails Wiki にあるドキュメントの翻訳です。
http://wiki.rubyonrails.org/rails/pages/HowToWriteAnActsAsFoxPlugin

Plugins を参照のこと。
SomeImportantPluginNotes を参照のこと。

◆ステップ1

# ruby script/generate plugin acts_as_fox

これで新しいディレクトリ「acts_as_fox」が vendor/plugins の下に作られる。

◆ステップ2
init.rb というファイルを作って,以下の行を追加する。

require 'acts_as_fox'

◆ステップ3
lib/acts_as_fox.rb というファイルにコードを追加する。

require 'active_record'

module Foo
  module Acts #:nodoc:
    module Fox #:nodoc:

      def self.included(mod)
        mod.extend(ClassMethods)
      end

      # declare the class level helper methods which
      # will load the relevant instance methods
      # defined below when invoked
      module ClassMethods
        def acts_as_fox
          class_eval do
            extend Foo::Acts::Fox::SingletonMethods
          end
          include Foo::Acts::Fox::InstanceMethods
        end
      end

      # Adds a catch_chickens class method which finds
      # all records which have a 'chickens' field set
      # to true.
      module SingletonMethods
        def catch_chickens
          find(:all, :conditions => ['chickens = ?', true])
        end
        # etc...
      end

      # Adds instance methods.
      module InstanceMethods
        def eat_chicken
          puts "Fox with ID #{self.id} just ate a chicken" 
        end
      end

    end
  end
end

# reopen ActiveRecord and include all the above to make
# them available to all our models if they want it

ActiveRecord::Base.class_eval do
  include Foo::Acts::Fox
end

◆ステップ4
最後に自分のクラスで新しいメソッドを使う。

class Thing < ActiveRecord::Base
  acts_as_fox
end

Jamis Buck は上記の Foo のような名前を使うことを推奨している。なぜなら「これは複数の開発者が同じ名前の機能を衝突を起こさずに開発することを許す」からだ。"Foo" の代わりに "ActiveRecord" を使う人々もいる。Jamis はこの使い方を好まない。彼は言う。「私はたくさんのプラグイン作者がこの特定のルートを使っていることに気づいていたが,私は絶対にお勧めしない。独自の act を ActiveRecord::Acts に追加する必然性はまったくない。代わりに独自の acts の名前空間(Fooのような)を作ることを推奨する」

【注意】もしクラスレベルの「宣言」メソッド(acts_as_fox)とその宣言のインタンスメソッドを定義しているモジュールが一対一にマッピングすることをあなたが保証するのなら,1つ以上のクラスレベルのヘルパーを定義することができる。したがって,おそらく SingletonMethods モジュールを FoxMethods のような名前に変えたいだろう。これは acts_as_fox と acts_slightly_foxy(SlightlyFoxy モジュール)と acts_as_fox_only_on_thursdays(FoxyThursdays モジュール)を,1つののプラグインで定義することを可能にする。