Module: Optimizely::Helpers::VariableType

Defined in:
lib/optimizely/helpers/variable_type.rb

Class Method Summary collapse

Class Method Details

.cast_value_to_type(value, variable_type, logger) ⇒ Object



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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/optimizely/helpers/variable_type.rb', line 25

def cast_value_to_type(value, variable_type, logger)
  # Attempts to cast the given value to the specified type
  #
  # value - The string value to cast
  # variable_type - String variable type
  #
  # Returns the cast value or nil if not able to cast
  return_value = nil

  case variable_type
  when 'boolean'
    return_value = value == 'true'
  when 'double'
    begin
      return_value = Float(value)
    rescue => e
      logger.log(Logger::ERROR, "Unable to cast variable value '#{value}' to type "\
                                "'#{variable_type}': #{e.message}.")
    end
  when 'integer'
    begin
      return_value = Integer(value)
    rescue => e
      logger.log(Logger::ERROR, "Unable to cast variable value '#{value}' to type "\
                                "'#{variable_type}': #{e.message}.")
    end
  when 'json'
    begin
      return_value = JSON.parse(value)
    rescue => e
      logger.log(Logger::ERROR, "Unable to cast variable value '#{value}' to type "\
                                "'#{variable_type}': #{e.message}.")
    end
  else
    # default case is string
    return_value = value
  end

  return_value
end