既然您说您只想在视图中执行此操作,那么我觉得视图助手值得考虑:
# view.html.haml
= value_for_view(:phone, @project)
# application_helper.rb
def value_for_view(attribute, object)
if overide_attributes_in_view? && object.respond_to?("#{attribute}_for_view")
object.send("#{attribute}_for_view")
else
object.send(attribute)
end
end
# application.rb
def overide_attributes_in_view?
#do your stuff here to determine whether the original values should be shown or the 'overloads'
end
# project.rb
def phone_for_view
nil # just add methods called "attribute_for_view" for whatever attributes you want to whatever models you want to have the attributes 'overloaded' (it's not really overloading, but it serves the purpose you describe)
end
或者类似地......你可以修补 AR::Base 以拥有一个 'value_for_view' 方法,所以视图看起来更像这样:
# view.html.haml
= @project.value_for_view(:phone)
# monkey_patch_file.rb
def value_for_view(attribute)
if respond_to?("#{attribute}_for_view")
send("#{attribute}_for_view")
else
send(attribute)
end
end
如果您坚持只能调用 @project.phone 并获取一个或其他值,则需要向 @project 传递一个标志,告诉它为您进行计算,如 Rovermicroer 的回答所示(不过,正如我评论的那样,我不确定'super'会起作用,但原理是正确的)。