문제

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