天天看點

HowTo Write An ActsAsChicken Plugin

From: http://wiki.rubyonrails.org/rails/pages/HowTosPlugins

See also Plugins

SomeImportantPluginNotes – before you start

Thanks to Kev Jackson and Jamis Buck for their help getting me started with writing acts_as_* plugins. This is a summary and plagiarism of their emails

This plugin adds a class method to a model that acts_as_chicken

A 6 step program to acting like a chicken…

Step 1

under your_app/vendor/plugins

create a directory “acts_as_chicken”

Step 2

in this directory create a lib directory

so now you should have

your_app/vendor/plugins/acts_as_chicken/lib

Step 3

in the acts_as_chicken directory create the following file with this content:

your_app/vendor/plugins/acts_as_chicken/init.rb

require 'acts_as_chicken'      

Step 4

in the lib subdirectory add your code to a file called acts_as_chicken.rb

your_app/vendor/plugins/acts_as_chicken/lib/acts_as_chicken.rb

require 'active_record'

module Foo
  module Acts #:nodoc:
    module Chicken #:nodoc:

      def self.append_features(base)
        super
        base.extend(ClassMethods)
      end

      module ClassMethods
        def acts_as_chicken
          class_eval do
            extend Foo::Acts::Chicken::SingletonMethods
          end
        end
      end

      # add your class methods here
      module SingletonMethods
        def cluck
          'cluck'
        end
        #etc...
      end

    end
  end
end

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

Step 5

Use your method in your classes

class Hen < ActiveRecord::Base
 acts_as_chicken
end
      

Step 6

Use your method in your view.

<%= Hen.cluck %>      

Jamis Buck suggested using some name like Foo in the above because “this will allow (potentially) multiple developers to develop identically-named features without conflict.” Other people use “ActiveRecord” in place of the three “Foo”. Jamis doesn’t like this use of ActiveRecord. He says “I’ve noticed many plugin developers taking this particular route, and I’d like to discourage it, strenuously. There really is no need to add your own acts to the ActiveRecord::Acts namespace. Instead, I’d encourage the creation of your own Acts namespace like Foo”

HowTosPlugins – Some tutorials to get started

What is missing here is a good description of the Ruby magic that is happening in step 4. Can someone in the know add this (then remove this message).

Updated on December 22, 2005 04:44 by Anonymous Coward (203.58.120.11)

繼續閱讀