Module: JunglePath::DBModel::Params

Defined in:
lib/jungle_path/db_model/params.rb

Class Method Summary collapse

Class Method Details

.convert_to_type(params, columns) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/jungle_path/db_model/params.rb', line 19

def self.convert_to_type(params, columns)
  #params must be hash of symbols (as keys) and values
  p = {}
  params = params.to_hash
  params.each do |k, v|
    column = columns[k]
    if column and v
      #puts "column, type: #{k} #{column.type}."
      if column.type == :integer or column.base_type == :integer
        p[k] = v.to_i
      elsif column.type == :timestamp and v.class == String
        p[k] = Time.parse(v).utc
      elsif column.type == :timestamp_local and v.class == String # experimental, probably won't use...
        p[k] = Time.parse(v)
      elsif column.type == :date and v.class == String
        p[k] = Date.parse(v).to_time
      elsif column.type == :date and v.class == Date
        p[k] = v.to_time
      elsif column.type == :boolean
        p[k] = to_bool(v)
      elsif (column.type == :string or column.base_type == :string) and v.class == String and v.strip.empty?
        # treat empty/whitespace only strings as nil.
        p[k] = nil
      else
        p[k] = v
      end
    else
      p[k] = v
    end
  end
  p
end

.symbolize(params) ⇒ Object



14
15
16
17
# File 'lib/jungle_path/db_model/params.rb', line 14

def self.symbolize(params)
  p = params.to_hash
  Hash[p.map {|k, v| [k.to_sym, v] }]
end

.to_bool(value) ⇒ Object

Raises:

  • (ArgumentError)


52
53
54
55
56
57
# File 'lib/jungle_path/db_model/params.rb', line 52

def self.to_bool(value)
  return false if value == nil
  return true  if value == true   || value =~ (/(true|t|yes|y|on|1)$/i)
  return false if value == false  || value.empty? || value =~ (/(false|f|no|n|off|0)$/i)
  raise ArgumentError.new("invalid value for Boolean: \"#{value}\"")
end

.transform(params, columns) ⇒ Object



4
5
6
7
8
9
10
11
12
# File 'lib/jungle_path/db_model/params.rb', line 4

def self.transform(params, columns)
  # sinatra params come as string keys with string values.
  # Convert values to various types based on Schema column definitions.
  # Convert keys to symbols.
  p = params.to_hash
  p = symbolize(p)
  p = convert_to_type(p, columns)
  p
end