Search code examples
rubypropertiesdatamapper

How to set a property in ruby datamapper that is a function of another property of the same object?


I want to add two new properties to a ruby datamapper model, one that is a date cast of a timestamp property and another that is a value from another object connected through a unique key.

So for the first case I have property :date, DateTime

and I want to add another property :date_date, Date that by default will be equal to date.to_date


Solution

  • You should see the docs: https://datamapper.org/docs/properties.html

    Specifically the sections on "Available Types" and "Setting default values".

    You can do it like this:

    property :date_date, Date, default: -> do |obj, prop|
      obj.date.to_date
    end
    

    You can alternatively set it through a callback (https://datamapper.org/docs/callbacks.html), for example:

    property :date_date, Date
    
    before_save :set_date_date
    
    def set_date_date
      self.date_date = date.to_date
    end
    

    Note it works basically the same way in Rails' ActiveRecord as well.