Module: DatetimeFormatter::HasDatetimeFormatter

Defined in:
lib/datetime_formatter/has_datetime_formatter.rb

Instance Method Summary collapse

Instance Method Details

#has_datetime_formatter(options = {}) ⇒ Object



4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/datetime_formatter/has_datetime_formatter.rb', line 4

def has_datetime_formatter(options = {})
   # custom format fields in hash format
   format_fields = (options[:custom_format] || {})
   # date time format
   default_format = options[:format] || "%d/%m/%Y"

   # if custom format fileds is empty then default created_at & updated_at
   format_fields.merge!({created_at: default_format}) unless format_fields.keys.include?(:created_at)

   format_fields.merge!({updated_at: default_format}) unless format_fields.keys.include?(:updated_at)

   format_fields.each do |attribute, field_format|
     define_method :"#{attribute}" do
       begin
         self[attribute].strftime(field_format || default_format)
       rescue
         self[attribute]
       end
     end

     define_method :"or_#{attribute}" do
       self[attribute]
     end
   end
end