以下是我的模块,其中我在n_attribute方法中序列化一个属性。
n_attrib_key是一个调用Object class
方法n_attrib
来创建动态方法的方法,
Object类也在下面给出。
我真正想要做的是将字段从User传递给Module HashDemo,序列化该字段,一旦字段被序列化,现在传递n_attrib_keys中的键,并在Object类中创建这些键的动态方法。 / p>
创建方法后,现在通过object的属性
调用这些方法正如我所说的方法,让我知道我在那种方法。现在我想将动态方法的名称(作为哈希的“关键”)和“值”存储到模型的属性中就像那样
@ user.address.home =“value”
@ user.address = {home:“value”}
有没有办法在define_method中获取调用者对象和属性,即在这种情况下谁调用了这个方法?
module HashDemo
def self.included(base)
base.extend(ClassMethods)
end
module ClassMethods
def n_attributes(*args)
args.each do |arg|
serialize %(:#{arg})
end
end
def n_attrib_keys(*names)
Object.n_attrib(*names)
end
end
end
class Object
def n_attrib(*names)
names.each do |name|
define_method("#{name}=") do |value|
puts "setter"
# @user.address = {"#{name}": value}
# i.e. @model.field = {key: value}
end
define_method("#{name}") do
puts "getter"
end
end
end
end
class User < ActiveRecord::Base
attr_accessible :address, :name
include HashDemo
n_attributes :address
n_attrib_keys :home, :location
u = User.new
u.address.home = value # this will go to the setter define_method in the Object class
u.address.home # this will go to the getter define_method in Object class
end