18 activerecord aggregate ruby-on-rails composite
什么时候应该使用ActiveRecord的composed_of类方法?
Sta*_*len 22
就个人而言,我认为当你有没有存储在数据库中的对象时,这很有用,如数据库中所示,例如温度,gps位置,平衡等.
您可能会问为什么那些没有存储在数据库中?在数据库中,我们只存储一个值,但是如果我们想要将有用的相关方法附加到该值,
例如
在温度升高的情况下,我们可能需要等的方法to_fahrenheit,to_celsius,is_boiling_point?,等
在GPS定位的情况下,我们可能需要等的方法distance_from(point),route_to(point)等
所以当我们可以为这些对象创建类时,它非常有用,并使用composed_of来动态初始化这些对象
希望它有帮助=)
如何使用 Money 的更composed_of复杂示例:
composed_of :price,
:class_name => "Money",
:mapping => [%w(cents cents), %w(currency currency_as_string)],
:constructor => Proc.new { |cents, currency| Money.new(cents || 0, currency || Money.default_currency) },
:converter => Proc.new { |value| value.respond_to?(:to_money) ? value.to_money : raise(ArgumentError, "Can't convert #{value.class} to Money") }
Run Code Online (Sandbox Code Playgroud)
来源:github 维基。