Question

I am using an ActiveModel model DateRange with attributes :from and :to and I want it to behave as follows..

  d = DateRange.new
=> #<DateRange:0x0000010532d3f8>
  d.from = "03/03/2010"
=> Wed, 03 Mar 2010
  d.to  = Date.today
=> Mon, 3 Mar 2014

In other words, whenever an attribute is set, if it is in string format it should be parsed into a date format.
Is there an ActiveModel callback function which will run immediately when an attribute is changed? If not, what would be best practice to do this?

Was it helpful?

Solution

You don't need any callbacks, what you need are custom setter methods:

class DateRange
  attr_reader :from, :to

  def from=(value)
    # implementation
  end

  def to=(value)
    # implementation
  end
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top