Module: Dronejob::Modules::Params

Extended by:
ActiveSupport::Concern
Included in:
Base
Defined in:
lib/dronejob/modules/params.rb

Instance Method Summary collapse

Instance Method Details

#convert_param(value, config) ⇒ Object



51
52
53
54
55
# File 'lib/dronejob/modules/params.rb', line 51

def convert_param(value, config)
  return nil if value.nil?

  return value
end

#param(key) ⇒ Object



46
47
48
49
# File 'lib/dronejob/modules/params.rb', line 46

def param(key)
  @params ||= {}
  @params[key.to_s]
end

#paramsObject



57
58
59
# File 'lib/dronejob/modules/params.rb', line 57

def params
  @params
end

#params=(params) ⇒ Object



25
26
27
# File 'lib/dronejob/modules/params.rb', line 25

def params=(params)
  @params = params.map { |name, value| [name, transform_parameter(name, value)] }.to_h
end

#transform_parameter(name, value) ⇒ Object



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/dronejob/modules/params.rb', line 29

def transform_parameter(name, value)
  if (config = self.class.param_config(name))
    return Base64.strict_decode64(value) if config[:type] == :base64
    return JSON.parse(Base64.strict_decode64(value)) if config[:type] == :json64

    if config[:type] == :numeric
      return Integer(value) if Integer(value) rescue false
      return Float(value) if Float(value) rescue false
    end
    if config[:type] == :boolean
      return true if value == "true"
      return false if value == "false"
    end
  end
  value
end

#validate_parameters!Object



61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
# File 'lib/dronejob/modules/params.rb', line 61

def validate_parameters!
  # Fill default parameters
  self.class.params.each do |param_name, param_config|
    param_value = @params[param_name.to_s]
    if param_value.nil? and param_config[:default]
      @params[param_name.to_s] = param_config[:default]
    end
  end

  # Validate parameters
  type_map = { string: ["String"], numeric: ["Fixnum", "Integer", "Float"], array: ["Array"], boolean: ["TrueClass", "FalseClass"], base64: ["String"], json64: ["Hash", "Array"] }
  self.class.params.each do |param_name, param_config|
    param_value = @params[param_name.to_s]
    if param_value.nil?
      fail ArgumentError, "Missing required parameter '#{param_name}' (#{param_config[:type]})" if param_config[:required]
    else
      allowed_classes = type_map[param_config[:type]]
      unless allowed_classes.include?(param_value.class.name)
        fail ArgumentError, "Invalid value '#{param_value}' for parameter '#{param_name}' (expected #{param_config[:type]}, got #{param_value.class.name})"
      end
    end
  end
end