Module: Decanter::Core::ClassMethods

Defined in:
lib/decanter/core.rb

Instance Method Summary collapse

Instance Method Details

#any_inputs_required?Boolean

Returns:

  • (Boolean)


86
87
88
# File 'lib/decanter/core.rb', line 86

def any_inputs_required?
  required_inputs.any?
end

#decant(args) ⇒ Object



57
58
59
60
61
62
63
64
65
66
# File 'lib/decanter/core.rb', line 57

def decant(args)
  return handle_empty_args if args.blank?
  return empty_required_input_error unless required_input_keys_present?(args)

  # Convert all params passed to a decanter to a hash with indifferent access to mitigate accessor ambiguity
  accessible_args = to_indifferent_hash(args)
  {}.merge( default_keys )
    .merge( unhandled_keys(accessible_args) )
    .merge( handled_keys(accessible_args) )
end

#decanter_for_handler(handler) ⇒ Object



195
196
197
198
199
200
201
# File 'lib/decanter/core.rb', line 195

def decanter_for_handler(handler)
  if specified_decanter = handler[:options][:decanter]
    Decanter::decanter_from(specified_decanter)
  else
    Decanter::decanter_for(handler[:assoc])
  end
end

#default_keysObject



68
69
70
71
72
73
74
75
76
# File 'lib/decanter/core.rb', line 68

def default_keys
  # return keys with provided default value when key is not defined within incoming args
  default_result = default_value_inputs
    .map { |input| [input[:key], input[:options][DEFAULT_VALUE_KEY]] }
    .to_h

  # parse default values
  handled_keys(default_result)
end

#default_value_inputsObject



78
79
80
# File 'lib/decanter/core.rb', line 78

def default_value_inputs
  handlers.values.select { |input| input[:options].key?(DEFAULT_VALUE_KEY) }
end

#empty_args_errorObject

Raises:

  • (ArgumentError)


109
110
111
# File 'lib/decanter/core.rb', line 109

def empty_args_error
  raise(ArgumentError, 'Decanter has required inputs but no values were passed')
end

#empty_required_input_errorObject



105
106
107
# File 'lib/decanter/core.rb', line 105

def empty_required_input_error
  raise(MissingRequiredInputValue, 'Required inputs have been declared, but no values for those inputs were passed.')
end

#handle(handler, args) ⇒ Object



142
143
144
145
146
# File 'lib/decanter/core.rb', line 142

def handle(handler, args)
  values = args.values_at(*handler[:name])
  values = values.length == 1 ? values.first : values
  self.send("handle_#{handler[:type]}", handler, values)
end

#handle_association(handler, args) ⇒ Object



154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
# File 'lib/decanter/core.rb', line 154

def handle_association(handler, args)
  assoc_handlers = [
    handler,
    handler.merge({
      key:   handler[:options].fetch(:key, "#{handler[:name]}_attributes").to_sym,
      name:  "#{handler[:name]}_attributes".to_sym
    })
  ]

  assoc_handler_names = assoc_handlers.map { |_handler| _handler[:name] }

  case args.values_at(*assoc_handler_names).compact.length
  when 0
    {}
  when 1
    _handler = assoc_handlers.detect { |_handler| args.has_key?(_handler[:name]) }
    self.send("handle_#{_handler[:type]}", _handler, args[_handler[:name]])
  else
    raise ArgumentError.new("Handler #{handler[:name]} matches multiple keys: #{assoc_handler_names}.")
  end
end

#handle_empty_argsObject



82
83
84
# File 'lib/decanter/core.rb', line 82

def handle_empty_args
  any_inputs_required? ? empty_args_error : {}
end

#handle_has_many(handler, values) ⇒ Object



176
177
178
179
180
181
182
183
184
185
186
187
188
189
# File 'lib/decanter/core.rb', line 176

def handle_has_many(handler, values)
  decanter = decanter_for_handler(handler)
  if values.is_a?(Hash)
    parsed_values = values.map do |index, input_values|
      next if input_values.nil?
      decanter.decant(input_values)
    end
    return { handler[:key] => parsed_values }
  else
    {
      handler[:key] => values.compact.map { |value| decanter.decant(value) }
    }
  end
end

#handle_has_one(handler, values) ⇒ Object



191
192
193
# File 'lib/decanter/core.rb', line 191

def handle_has_one(handler, values)
  { handler[:key] => decanter_for_handler(handler).decant(values) }
end

#handle_input(handler, args) ⇒ Object



148
149
150
151
152
# File 'lib/decanter/core.rb', line 148

def handle_input(handler, args)
   values = args.values_at(*handler[:name])
   values = values.length == 1 ? values.first : values
   parse(handler[:key], handler[:parsers], values, handler[:options])
end

#handled_keys(args) ⇒ Object



128
129
130
131
132
133
134
135
136
137
138
139
140
# File 'lib/decanter/core.rb', line 128

def handled_keys(args)
  arg_keys = args.keys.map(&:to_sym)
  inputs, assocs = handlers.values.partition { |handler| handler[:type] == :input }

  {}.merge(
    # Inputs
    inputs.select     { |handler| (arg_keys & handler[:name]).any? }
          .reduce({}) { |memo, handler| memo.merge handle_input(handler, args) }
  ).merge(
    # Associations
    assocs.reduce({}) { |memo, handler| memo.merge handle_association(handler, args) }
  )
end

#handlersObject



212
213
214
# File 'lib/decanter/core.rb', line 212

def handlers
  @handlers ||= {}
end

#has_many(assoc, **options) ⇒ Object



28
29
30
31
32
33
34
35
36
# File 'lib/decanter/core.rb', line 28

def has_many(assoc, **options)
  handlers[assoc] = {
    assoc:   assoc,
    key:     options.fetch(:key, assoc),
    name:    assoc,
    options: options,
    type:    :has_many
  }
end

#has_one(assoc, **options) ⇒ Object



38
39
40
41
42
43
44
45
46
# File 'lib/decanter/core.rb', line 38

def has_one(assoc, **options)
  handlers[assoc] = {
    assoc:   assoc,
    key:     options.fetch(:key, assoc),
    name:    assoc,
    options: options,
    type:    :has_one
  }
end

#ignore(*args) ⇒ Object



48
49
50
# File 'lib/decanter/core.rb', line 48

def ignore(*args)
  keys_to_ignore.push(*args).map!(&:to_sym)
end

#input(name, parsers = nil, **options) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/decanter/core.rb', line 11

def input(name, parsers=nil, **options)
  # Convert all input names to symbols to correctly calculate handled vs. unhandled keys
  input_names = [name].flatten.map(&:to_sym)

  if input_names.length > 1 && parsers.blank?
    raise ArgumentError.new("#{self.name} no parser specified for input with multiple values.")
  end

  handlers[input_names] = {
    key:     options.fetch(:key, input_names.first),
    name:    input_names,
    options: options,
    parsers:  parsers,
    type:    :input
  }
end

#keys_to_ignoreObject



216
217
218
# File 'lib/decanter/core.rb', line 216

def keys_to_ignore
  @keys_to_ignore ||= []
end

#parse(key, parsers, value, options) ⇒ Object



203
204
205
206
207
208
209
210
# File 'lib/decanter/core.rb', line 203

def parse(key, parsers, value, options)
  return { key => value } unless parsers
  if options[:required] && value_missing?(value)
    raise ArgumentError.new("No value for required argument: #{key}")
  end
  parser_classes = Parser.parsers_for(parsers)
  Parser.compose_parsers(parser_classes).parse(key, value, options)
end

#required_input_keys_present?(args = {}) ⇒ Boolean

Returns:

  • (Boolean)


97
98
99
100
101
102
103
# File 'lib/decanter/core.rb', line 97

def required_input_keys_present?(args={})
  return true unless any_inputs_required?
  compact_inputs = required_inputs.compact
  compact_inputs.all? do |input|
    args.keys.map(&:to_sym).include?(input) && !args[input].nil?
  end
end

#required_inputsObject



90
91
92
93
94
95
# File 'lib/decanter/core.rb', line 90

def required_inputs
  handlers.map do |h|
    options = h.last[:options]
    h.first.first if options && options[:required]
  end
end

#strict(mode) ⇒ Object

Raises:

  • (ArgumentError)


52
53
54
55
# File 'lib/decanter/core.rb', line 52

def strict(mode)
  raise(ArgumentError, "#{self.name}: Unknown strict value #{mode}") unless [true, false].include? mode
  @strict_mode = mode
end

#strict_modeObject



220
221
222
# File 'lib/decanter/core.rb', line 220

def strict_mode
  @strict_mode.nil? ? Decanter.configuration.strict : @strict_mode
end

#unhandled_keys(args) ⇒ Object

protected

Raises:



115
116
117
118
119
120
121
122
123
124
125
126
# File 'lib/decanter/core.rb', line 115

def unhandled_keys(args)
  unhandled_keys = args.keys.map(&:to_sym) -
    handlers.keys.flatten.uniq -
    keys_to_ignore -
    handlers.values
      .select { |handler| handler[:type] != :input }
      .map { |handler| "#{handler[:name]}_attributes".to_sym }

  return {} unless unhandled_keys.any?
  raise(UnhandledKeysError, "#{self.name} received unhandled keys: #{unhandled_keys.join(', ')}.") if strict_mode
  args.select { |key| unhandled_keys.include? key.to_sym }
end