为Rails编写acts_as_fox插件
第一步
创建一个空的 plugin:
script/generate plugin acts_as_fox这个命令将在 your_app/vendor/plugins 目录下创建一个名为 acts_as_fox 的目录,并且这个目录下会包含一些初试文件。
第二步
编辑 init.rb 文件,加入以下内容:
require 'acts_as_fox'
第三步
编辑 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
第四步
最后在你的模型中使用 acts_as_fox
class Thing < ActiveRecord::Base acts_as_fox end
发表评论
| Trackback
