Rails-如何为类内的方法列表动态定义setter/getter



我有一个通知模块,它有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/sette,因为我不想为每个方法编写getter/seter,而且我不确定我有多少方法->将来可能会扩展}

     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方法

OpenStruct是一种类似于哈希的数据结构,它允许定义任意属性及其伴随值。这是通过使用Ruby的元编程来定义类本身的方法来实现的。

示例:

require 'ostruct'
hash = { "country" => "Australia", :population => 20_000_000 }
data = OpenStruct.new(hash)
p data        # -> <OpenStruct country="Australia" population=20000000>

使用Ruby OpenStruct类。它将在不定义此类代码的情况下满足您的需求。

Edit1,示例:

require 'ostruct'
class Aeroplane < OpenStruct; end
a = Aeroplane.new(:p => :true, :q => :true)
a.p # => true

最新更新