chronic_duration_attribute.rb 1.35 KB
Newer Older
1 2 3 4
module ChronicDurationAttribute
  extend ActiveSupport::Concern

  class_methods do
5
    def chronic_duration_attr_reader(virtual_attribute, source_attribute)
6
      define_method(virtual_attribute) do
7
        chronic_duration_attributes[virtual_attribute] || output_chronic_duration_attribute(source_attribute)
8 9 10
      end
    end

11
    def chronic_duration_attr_writer(virtual_attribute, source_attribute, parameters = {})
12
      chronic_duration_attr_reader(virtual_attribute, source_attribute)
13

14
      define_method("#{virtual_attribute}=") do |value|
15
        chronic_duration_attributes[virtual_attribute] = value.presence || parameters[:default].presence.to_s
16

17
        begin
18
          new_value = value.present? ? ChronicDuration.parse(value).to_i : parameters[:default].presence
19 20 21
          assign_attributes(source_attribute => new_value)
        rescue ChronicDuration::DurationParseError
          # ignore error as it will be caught by validation
22 23
        end
      end
24

25
      validates virtual_attribute, allow_nil: true, duration: true
26
    end
27 28 29 30 31 32 33 34 35 36 37

    alias_method :chronic_duration_attr, :chronic_duration_attr_writer
  end

  def chronic_duration_attributes
    @chronic_duration_attributes ||= {}
  end

  def output_chronic_duration_attribute(source_attribute)
    value = attributes[source_attribute.to_s]
    ChronicDuration.output(value, format: :short) if value
38 39
  end
end