Module: Abid::ParamsParser

Defined in:
lib/abid/params_parser.rb

Class Method Summary collapse

Class Method Details

.parse(params, specs) ⇒ Object



4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# File 'lib/abid/params_parser.rb', line 4

def parse(params, specs)
  specs.map do |name, spec|
    if params.include?(name)
      value = type_cast(params[name], spec[:type])
    elsif ENV.include?(name.to_s)
      value = type_cast(ENV[name.to_s], spec[:type])
    elsif spec.key?(:default)
      value = spec[:default]
    else
      fail "param #{name} is not specified"
    end

    [name, value]
  end.to_h
end

.type_cast(value, type) ⇒ Object



20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/abid/params_parser.rb', line 20

def type_cast(value, type)
  case type
  when :boolean then value == true || value == 'true'
  when :int then value.to_i
  when :float then value.to_f
  when :string then value.to_s
  when :date then type_cast_date(value)
  when :datetime, :time then type_cast_time(value)
  when nil then value
  else fail "invalid type: #{type}"
  end
end

.type_cast_date(value) ⇒ Object



33
34
35
36
37
38
39
# File 'lib/abid/params_parser.rb', line 33

def type_cast_date(value)
  case value
  when Date then value
  when Time, DateTime then value.to_date
  else Date.parse(value.to_s)
  end
end

.type_cast_time(value) ⇒ Object



41
42
43
44
45
46
47
# File 'lib/abid/params_parser.rb', line 41

def type_cast_time(value)
  case value
  when Date then value.to_time
  when Time, DateTime then value
  else Time.parse(value.to_s)
  end
end