質問

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?

役に立ちましたか?

解決

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
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top