【问题标题】:Using class_eval to overwrite an association使用 class_eval 覆盖关联
【发布时间】:2012-07-30 11:01:52
【问题描述】:

我有一个具有以下关系的消息模型:

belongs_to :sender, Class: "User"
belongs_to :recipient, Class: "User"

我正在尝试在某些情况下使用 class_eval 覆盖接收者方法。

这行得通:

def update_recipient(message, recipient_addition = nil)
  message.class_eval <<-EVAL
    def recipient
      "test"
    end
  EVAL
end

message.recipient => "测试"

但是,这不是:

def update_recipient(message, recipient_addition = nil)
  message.class_eval <<-EVAL
    def recipient
      [#{message.recipient}, #{recipient_addition}]
    end
  EVAL
end

(eval):3: syntax error, unexpected keyword_end, expecting ']'

【问题讨论】:

    标签: ruby ruby-on-rails-3 metaprogramming


    【解决方案1】:

    第一个 # 被误解为注释字符,丢弃了该行的其余部分。 #{} 预计会插入双引号内,但现在似乎没有理由将它们放在 #{} 中,因为它们只是简单的字符串值。

    ["#{message.recipient}", "#{recipient_addition}"]
    

    ...除非您计划类似:

    ["To: #{message.recipient}", "CC: #{recipient_addition}"]
    

    【讨论】:

    • 在您看来,返回包含用户对象的数组的最佳方式是什么?
    • 那些看起来是您要返回的对象,因此如果您想返回 string 值,请执行[message.recipient.email, recipient_addition.email] 之类的操作(假设它们具有电子邮件属性)。如果你想返回objects,直接通过[message.recipient, recipient_addition]返回即可
    • 很遗憾,receiver_addition 不在该 class_eval 块的范围内。
    猜你喜欢
    • 2012-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-22
    • 2019-07-23
    • 1970-01-01
    • 2020-11-22
    相关资源
    最近更新 更多