2014年9月19日 星期五

[Ruby] module 內的用法.


一些module 常看到的用法:

class_variable_get 和 class_variable_set 這兩個方法, 就是取得 class_variable 的method,
因為在module 被 其他 class extend 後, 這method 就起作用了.

另外還有 class_eval 的用法. 

def self.included(base) base.send(:include, ActiveModel::Naming) base.send(:include, ActiveModel::Conversion) base.send(:include, ActiveModel::Dirty) base.extend ClassMethods end module ClassMethods class_variable_get(:@@attributes).each do |attr| class_eval <<-EVAL @@all_attributes << "#{attr}".to_sym define_method "#{attr}" do @#{attr} end define_method "#{attr}?" do #{attr} ? true : false end # writable attributes with dirty support define_method "#{attr}=" do |value| return if value == @#{attr} #{attr}_will_change! @#{attr} = value end EVAL end end

這邊可以看到 instance_eval 的用法:
def self.included(base) base.extend ClassMethods end def ClassMethods def has_many(klass_sym) prefix = "Objects::" klass_name = prefix + klass_sym.to_s.classify instance_eval do define_method "#{klass_sym}" do klass = klass_name.constantize klass.where("#{self.remote_name}Id = '#{self.id}'") end end end end

【下列文章您可能也有興趣】

沒有留言: