如何使用猴子修补在define_method中获取调用者对象和字段名称?

时间:2014-12-17 10:54:26

标签: ruby-on-rails ruby ruby-on-rails-3 activerecord ruby-on-rails-3.2

以下是我的模块,其中我在n_attribute方法中序列化一个属性。 n_attrib_key是一个调用Object class方法n_attrib来创建动态方法的方法, Object类也在下面给出。

我真正想要做的是将字段从User传递给Module HashDemo,序列化该字段,一旦字段被序列化,现在传递n_attrib_keys中的键,并在Object类中创建这些键的动态方法。 / p>

创建方法后,现在通过object的属性

调用这些方法

现在我面临的主要问题是

正如我所说的方法,让我知道我在那种方法。现在我想将动态方法的名称(作为哈希的“关键”)和“值”存储到模型的属性中就像那样

称为

  

@ user.address.home =“value”

我想在define_method

中得到什么
  

@ 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

0 个答案:

没有答案