如何猴子修补别名属性

时间:2015-03-27 13:29:38

标签: ruby-on-rails monkeypatching

我有一个数据库,其字段'update'对应于updated_at。 该数据库不仅由rails应用程序使用,而且当前无法迁移该字段。

在我的模型中,我想在属性上创建一个别名:

class Model < ActiveRecord::Base
  alias_attribute 'updated_at', 'update'
  ...
end

但是这会调用模型的更新方法。

所以我在这里找到了alias_attribute定义:github code

我希望通过以下方式修补此问题:

def self.alias_attribute(new_name, old_name)
  module_eval <<-STR, __FILE__, __LINE__ + 1
    def #{new_name}; self.attributes[#{old_name}]; end
    def #{new_name}?; self.attributes[#{old_name}?; end
    def #{new_name}=(v); self.attributes[#{old_name} = v; end
  STR
end

我怎样才能做到这一点?

0 个答案:

没有答案