Class: DateParams::Parser

Inherits:
Object
  • Object
show all
Defined in:
lib/date_params/parser.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(param, options, params) ⇒ Parser

Returns a new instance of Parser.



13
14
15
16
17
18
19
# File 'lib/date_params/parser.rb', line 13

def initialize(param, options, params)
  @param = param
  @options = options
  @params = params
  @date_format =  options.fetch :date_format, default_date_format
  @time_format =  options.fetch :time_format, default_time_format
end

Instance Attribute Details

#date_formatObject (readonly)

Returns the value of attribute date_format.



12
13
14
# File 'lib/date_params/parser.rb', line 12

def date_format
  @date_format
end

#optionsObject (readonly)

Returns the value of attribute options.



12
13
14
# File 'lib/date_params/parser.rb', line 12

def options
  @options
end

#paramObject (readonly)

Returns the value of attribute param.



12
13
14
# File 'lib/date_params/parser.rb', line 12

def param
  @param
end

#paramsObject (readonly)

Returns the value of attribute params.



12
13
14
# File 'lib/date_params/parser.rb', line 12

def params
  @params
end

#time_formatObject (readonly)

Returns the value of attribute time_format.



12
13
14
# File 'lib/date_params/parser.rb', line 12

def time_format
  @time_format
end

Instance Method Details

#parse_date_param!(field = param) ⇒ Object



21
22
23
24
25
26
27
# File 'lib/date_params/parser.rb', line 21

def parse_date_param!(field = param)
  date_string = traversed_params.try(:[], field)
  return if date_string.blank?
  inferred_date_format = date_string =~ /\d{4}-\d{2}-\d{2}/ ? '%Y-%m-%d' : date_format
  date = Date.strptime(date_string, inferred_date_format)
  traversed_params[field] = date if date
end

#parse_datetime_param!Object



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/date_params/parser.rb', line 29

def parse_datetime_param!
  if param.is_a? Hash
    fields = param
    fields.assert_valid_keys :date, :time, :field
  else
    fields = {
        date: "#{param}_date".to_sym,
        time: "#{param}_time".to_sym,
        field: param
    }
  end

  date = parse_date_param! fields[:date]
  return if date.blank?
  time_string = traversed_params.try(:[], fields[:time])
  return if time_string.blank?
  datetime_format = "%Y-%m-%dT#{time_format}%z"
  datetime_string = "#{date.iso8601}T#{time_string}#{Time.zone.name}"
  datetime = Time.strptime(datetime_string, datetime_format).in_time_zone(Time.zone)
  traversed_params[fields[:field]] = datetime if datetime
end