Rails中的composed_of – 什么时候使用它?

什么时候应该使用ActiveRecord的composed_of类方法?

就个人而言,我认为当你有没有存储在数据库中的对象时,这很有用,如数据库中所示,例如温度,gps位置,平衡等。

您可能会问为什么那些不存储在数据库中? 在数据库中我们只存储一个值,但如果我们想要将有用的相关方法附加到该值,

例如

  1. 在温度的情况下,我们可能需要像to_fahrenheitto_celsiusis_boiling_point? 等等

  2. 在gps位置的情况下,我们可能需要像distance_from(point)route_to(point)等方法

所以当我们可以为这些对象创建类时,它非常有用,并使用composed_of来动态初始化这些对象

希望它有帮助=)

一个更复杂的例子,说明如何使用composed_of和Money :

 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") } 

资料来源: github wiki 。