我在我的一个项目中使用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=
我尝试使用方法缺失但是如果方法以“=”结束,我需要解析它并检查这些键的属性,所以我不喜欢代码的样子。
答案 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