Module: Admin::DatetimeFieldConcern::ClassMethods

Defined in:
lib/generators/infold/templates/install/app/models/concerns/admin/datetime_field_concern.rb

Instance Method Summary collapse

Instance Method Details

#datetime_field(field_name) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/generators/infold/templates/install/app/models/concerns/admin/datetime_field_concern.rb', line 10

def datetime_field(field_name)
  attr_reader "#{field_name}_date", "#{field_name}_time"

  define_method("#{field_name}_date=") do |val|
    instance_variable_set("@#{field_name}_date", convert_date(val))
    send("set_#{field_name}")
  end

  define_method("#{field_name}_time=") do |val|
    instance_variable_set("@#{field_name}_time", convert_time(val))
    send("set_#{field_name}")
  end

  define_method("set_#{field_name}") do
    send("#{field_name}=", convert_datetime(instance_variable_get("@#{field_name}_date"), instance_variable_get("@#{field_name}_time")))
  end

  define_method("#{field_name}_date") do
    instance_variable_get("@#{field_name}_date") || (send(field_name) ? I18n.l(send(field_name).to_date) : nil)
  end

  define_method("#{field_name}_time") do
    instance_variable_get("@#{field_name}_time") || send(field_name)&.strftime('%R')
  end

  validates "#{field_name}_date", presence: true, if: -> { send("#{field_name}_time").present? }
  validates "#{field_name}_time", presence: true, if: -> { send("#{field_name}_date").present? }
end