我正在制作一个插件,我需要它来覆盖我的模型的setter / getter。这是我到目前为止的代码:
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
参数。如果我在评估的代码中打印它,它会打印设置属性时出现的正确值,但是如果我在发送它的ip2long
函数内打印它会返回一个字符串:raw_value
那么怎么做我传递这个参数而不将其解释为字符串?
答案 0 :(得分: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