2018-02-20 19:09:59 -05:00
|
|
|
module ChronicDurationAttribute
|
|
|
|
extend ActiveSupport::Concern
|
|
|
|
|
|
|
|
class_methods do
|
2018-02-26 10:26:39 -05:00
|
|
|
def chronic_duration_attr_reader(virtual_attribute, source_attribute)
|
2018-02-20 19:09:59 -05:00
|
|
|
define_method(virtual_attribute) do
|
2018-03-22 19:12:15 -04:00
|
|
|
chronic_duration_attributes[virtual_attribute] || output_chronic_duration_attribute(source_attribute)
|
2018-02-20 19:09:59 -05:00
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2018-04-04 15:31:56 -04:00
|
|
|
def chronic_duration_attr_writer(virtual_attribute, source_attribute, parameters = {})
|
2018-03-22 19:12:15 -04:00
|
|
|
chronic_duration_attr_reader(virtual_attribute, source_attribute)
|
2018-03-21 12:22:52 -04:00
|
|
|
|
2018-02-20 19:09:59 -05:00
|
|
|
define_method("#{virtual_attribute}=") do |value|
|
2018-04-04 15:31:56 -04:00
|
|
|
chronic_duration_attributes[virtual_attribute] = value.presence || parameters[:default].presence.to_s
|
2018-03-22 19:12:15 -04:00
|
|
|
|
2018-03-21 12:22:52 -04:00
|
|
|
begin
|
2018-04-04 15:31:56 -04:00
|
|
|
new_value = value.present? ? ChronicDuration.parse(value).to_i : parameters[:default].presence
|
2018-03-22 19:12:15 -04:00
|
|
|
assign_attributes(source_attribute => new_value)
|
|
|
|
rescue ChronicDuration::DurationParseError
|
|
|
|
# ignore error as it will be caught by validation
|
2018-03-21 12:22:52 -04:00
|
|
|
end
|
|
|
|
end
|
2018-02-28 14:56:14 -05:00
|
|
|
|
2018-03-22 19:12:15 -04:00
|
|
|
validates virtual_attribute, allow_nil: true, duration: true
|
2018-02-20 19:09:59 -05:00
|
|
|
end
|
2018-03-22 19:12:15 -04:00
|
|
|
|
|
|
|
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
|
2018-02-20 19:09:59 -05:00
|
|
|
end
|
|
|
|
end
|