24

When should you use ActiveRecord's composed_of class method?

Damien Wilson
  • 4,540
  • 3
  • 21
  • 27
  • 2
    There's a nice example in the comments of that page. – ryeguy Apr 27 '10 at 02:39
  • @ryeguy, thanks, read that before posting but it doesn't demonstrate or discuss where you'd benefit from it. (Missing the higher-level view.) –  Apr 27 '10 at 03:12
  • Have you read this one http://api.rubyonrails.org/classes/ActiveRecord/Aggregations/ClassMethods.html ? – Corey Apr 27 '10 at 04:40

2 Answers2

28

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 =)

BinaryButterfly
  • 18,137
  • 13
  • 50
  • 91
Staelen
  • 7,691
  • 5
  • 34
  • 30
  • So composed_of initializes the obj coming OUT of the db. Can you assign the same object GOING INTO the db? obj.temperature = my_temp_obj. And if so, what method does it call on the value obj to convert it to the db format, be that int,varchar, etc? – pixelearth Aug 29 '11 at 04:52
  • hi @pixelearth, as mentioned, the values are not stored in database =) – Staelen Sep 21 '11 at 11:41
5

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.

Florin
  • 1,844
  • 2
  • 16
  • 21