2012-07-13 144 views
1

我正在制作一个插件,我需要它来覆盖我的模型的setter/getter。这里是我到目前为止的代码:rails 3覆盖模型设置器

module Iplong 
    extend ActiveSupport::Concern 

    module ClassMethods 
     ... 

     def override_setter 
      self.class_eval %(
       def #{attribute}=(raw_value) 
        self[:#{attribute}] = #{ip2long('raw_value')} 
       end 
      ) 
     end 
    end 

end 

ActiveRecord::Base.send :include, Iplong 

通知的raw_value PARAM。如果我将它打印在评估代码中,它将打印出属性设置时出现的正确值,但如果我在ip2long函数中打印它,它将返回一个字符串:raw_value,那么如何在不解释它的情况下传递此参数作为字符串?

回答

0

您的问题是在这个特定的代码块:

"#{ip2long('raw_value')}" 

从字符串Ruby代码翻译这一点,你会得到:

ip2long('raw_value') 

所以你实际发送“RAW_VALUE '字符串而不是该变量的实际值。

与替换代码:

"#{ip2long(raw_value)}" 

而且你应该罚款。

编辑:此示例代码展示了它会如何工作:

class A 
    attr_accessor :ip 

    def ip2num(ip) 
    ip.gsub(".", "") 
    end 

    def override(attr) 
    code = "def #{attr}=(value); @ip = ip2num(value); end" 
    self.class.class_eval(code) 
    end 
end 

a = A.new 
a.ip = "0.0.0.0" 
puts a.ip 

a.override("ip") 
a.ip = "0.0.0.0" 
puts a.ip 
+0

尝试,但我得到'未定义的局部变量或方法'RAW_VALUE”为#<类别:0x00000003bc72a0>' – 2012-07-13 17:49:04

+0

不知道在哪里概率。可能是,但我编辑答案,包括一些示例代码,应该可以帮助你明白我的意思。 – 2012-07-13 17:59:04