【问题标题】:On call of attribute_foo=(bar), call custom code, to change bar调用attribute_foo=(bar),调用自定义代码,改变bar
【发布时间】:2012-04-12 09:26:01
【问题描述】:

由于某种原因,一个简单的piece of decorator-code 在我的生产机器上失败了,但在开发中运行良好[1]。

我把它弄傻了,发现以下是最简单的失败部分:

Spree::Variant.class_eval do
  def price=(value)
    self.price = normalize_number(value)
  end
end

SystemStackError (stack level too deep): 失败

调试告诉我,该函数确实一直被调用。 self.price= 调用 price=。

解决这个问题的常用 Rails/Ruby 模式是什么?我想要的是:

attribute_foo=(bar) 被调用时,将其委托给我的自定义代码,在那里我可以通过一小段自定义代码运行传递的bar。然后将更改后的bar 分配给attribute_foo。

[1]: 唯一的区别是 Ruby 补丁版本和生产机器有 64 位版本,而开发机器上的 32 位版本:ruby 1.8.7 (2011-02-18 patchlevel 334) [x86_64-linux]

【问题讨论】:

    标签: ruby-on-rails-3 attributes decorator


    【解决方案1】:

    解决方法很简单:只需使用write_attribute

    Spree::Variant.class_eval 做 def价格=(价值) write_attribute(:price, bar(value)) 结尾 结束

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-09
      • 1970-01-01
      相关资源
      最近更新 更多