在ruby on rails3 的guides,插件扩展中有这样一段代码
http://guides.rubyonrails.org/plugins.html#add-an-instance-method
module Yaffle
def self.included(base)
base.send :extend, ClassMethods
end
module ClassMethods
def acts_as_yaffle(options = {})
cattr_accessor :yaffle_text_field
self.yaffle_text_field = (options[:yaffle_text_field] || :last_squawk).to_s
send :include, InstanceMethods
end
end
module InstanceMethods
def squawk(string)
write_attribute(self.class.yaffle_text_field, string.to_squawk)
end
end
end
ActiveRecord::Base.send :include, Yaffle
还可以有几种写法:
A:
module Yaffle def self.included(base) base.send :extend, ClassMethods base.send :include, InstanceMethods end 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 end module InstanceMethods def squawk(string) write_attribute(self.class.yaffle_text_field, string.to_squawk) end end end ActiveRecord::Base.send :include, Yaffle
B:
module Yaffle
def self.included(base)
base.send :extend, ClassMethods
base.class_eval do
include InstanceMethods
end
end
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
end
module InstanceMethods
def squawk(string)
write_attribute(self.class.yaffle_text_field, string.to_squawk)
end
end
end
ActiveRecord::Base.send :include, Yaffle
C:
module Yaffle
def self.included(base)
base.send :extend, ClassMethods
end
module ClassMethods
def self.extended(base)
base.send :include, InstanceMethods
end
def acts_as_yaffle(options = {})
cattr_accessor :yaffle_text_field
self.yaffle_text_field = (options[:yaffle_text_field] || :last_squawk).to_s
end
end
module InstanceMethods
def squawk(string)
write_attribute(self.class.yaffle_text_field, string.to_squawk)
end
end
end
ActiveRecord::Base.send :include, Yaffle
[1]http://vincent253.iteye.com/blog/135213