composed_of in Rails - when to use it?

北城余情 提交于 2019-12-02 21:43:05

personally, i think this is useful when you have objects which are not stored in database, as shown in the database, e.g. temperature, gps location, balance, etc.

You might ask then why those are not stored in the database? In the database we only store a value, but if we want to attach useful, relevant methods to that value,

for e.g.

  1. in the case of temperature, we might need methods like to_fahrenheit, to_celsius, is_boiling_point?, etc

  2. in the case of gps location, we might need methods like distance_from(point), route_to(point), etc

so it's pretty useful when we can just create the classes for these objects, and use composed_of to initialize these objects on the fly

hope it helps =)

A more complex example of how to use composed_of with 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") }

Source: github wiki.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!