【发布时间】:2014-11-06 19:50:12
【问题描述】:
我有一个通知模块,其中包含 1)汽车 2)自行车 3)飞机等类。我在 UserFeature 模型中有一个序列化列。我有一个模块“通知”,其中包含 11 个类的列表。
Notifications
1)car
2)bike
3)Aeroplane
UserFeature 模型中通知栏的哈希结构必须是
{:car => {:mirror => :true, :door => :true}
:bike => {:x=> :true, :x => :true}
:Aeroplane => {:p => :true, :q => :true}
}
我可以访问 user_object.Notifications 但是为了访问 user_object.car 和 user_object.mirror 我需要编写 getter/setter 方法 { 动态定义 getter/setter 因为我不想为每个方法编写 getter/setter 而且我不确定数字我拥有的方法 -> 将来可能会扩展 }
Notifications.constants.each do |notification_class|
class_methods = "Notifications::#{notification_class}".constantize.methods(false)
class_methods.each do |method|
method_name = method[0..-4].split('(')[0]
setter_getter_name = "#{notification_class.to_s.underscore}_#{method_name}"
define_method("#{setter_getter_name}=") do |value|
self.notifications = GlobalUtils.form_hash(self.notifications, "#{notification_class}".to_sym, "#{method_name}".to_sym)
self[:notifications]["#{notification_class}".to_sym][ "#{method_name}".to_sym] = value
end
define_method("#{setter_getter_name}") do
self.notifications.fetch("#{notification_class_name}".to_sym, {}).fetch("#{method_name}".to_sym)
end
end
end
但是当我尝试访问 user_object.mirror 时,
undefined method for #<UserFeature000043645345>
我做错了什么? 我只需要使用 getter/setter 方法来做到这一点
【问题讨论】:
标签: ruby-on-rails dynamic getter-setter