Skip to content

Instantly share code, notes, and snippets.

@begin29
Last active December 9, 2016 18:23
Show Gist options
  • Save begin29/7210d9830ecab538ee10dbb21860b8e2 to your computer and use it in GitHub Desktop.
Save begin29/7210d9830ecab538ee10dbb21860b8e2 to your computer and use it in GitHub Desktop.
composed_of for manipulating ValueObjects add composition class to active_record class with additional information and ability to write value converter
#If we have following code in model:
composed_of :temperature, :mapping => %w(celsius)
#Then our composition class can be this:
class Temperature
def initialize(celsius)
@celsius = celsius
end
# This method is called by ActiveRecord, when record is saved.
# Result of this method will be stored in table in "celsius" field,
# and later when the record is loaded again, this will go to
# our Temperature#new constructor.
def celsius
@celsius
end
# This is example of method that we can add to make this composition useful.
def farenheit
@celsius * 9/5 + 32
end
end
# detailed example http://api.rubyonrails.org/classes/ActiveRecord/Aggregations/ClassMethods.html#method-i-composed_of
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment