实例对象中的ActiveModel动态方法

时间:2012-01-10 16:24:54

标签: ruby-on-rails ruby metaprogramming activemodel

我在我的一个项目中使用ActiveModel,我想问下一种情况下动态方法定义的最佳方法

Base ActiveModel类只有一个名为attributes的访问者属性。

  def initialize(attributes = {})
      set_default_attributes!
      @attributes.merge!(attributes.symbolize_keys)
      @new_record = true    
   end

   def read_attribute_for_validation(key)
      @attributes[key]
   end


   def self.create(attributes={})
     obj = self.new(attributes)
     obj.save
     return obj
   end

   def save
     if self.valid?
       puts "saved!"
       return true
     end   
     return false
  end    


  def update_attributes(attributes={})
     self.attributes.merge!(attributes.symbolize_keys)
     self.save
  end     



  def as_json(options={})
      hash = Hash.new
      hash.merge!(self.attributes)
      hash.as_json({:root=>false}.merge!(options || {}))

  end  

方法应该像访问者一样,但应该使用内部@attributes变量

示例@attributes是否为{:param1=>1,:param2=>2}

的哈希值

实例对象应该有下一个方法

param1
param1=
param2
param2=

我尝试使用方法缺失但是如果方法以“=”结束,我需要解析它并检查这些键的属性,所以我不喜欢代码的样子。

1 个答案:

答案 0 :(得分:1)

您可以使用singleton_class.module_eval

添加方法
def initialize(attributes = {})
   set_default_attributes!
   @attributes.each do |key,value|
     singleton_class.module_eval do
       define_method(key) { self.attributes[key] } unless method_defined? key
       define_method("#{key}=") { |new_value|  self.attributes[key] = new_value } unless method_defined? "#{key}="
     end
   end
   @attributes.merge!(attributes.symbolize_keys)
   @new_record = true

 end