Class: ParamsTransformer::Transformer

Inherits:
Object
  • Object
show all
Defined in:
lib/params_transformer/transformer.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(args) ⇒ Transformer

Returns a new instance of Transformer.



6
7
8
9
10
# File 'lib/params_transformer/transformer.rb', line 6

def initialize(args)
  @params = Rails.version[0].to_i > 4 ? args.to_h.with_indifferent_access : HashWithIndifferentAccess.new(args)
  @inputs = set_inputs
  after_init(@params)
end

Instance Attribute Details

#inputsObject

Returns the value of attribute inputs.



3
4
5
# File 'lib/params_transformer/transformer.rb', line 3

def inputs
  @inputs
end

#paramsObject (readonly)

Returns the value of attribute params.



3
4
5
# File 'lib/params_transformer/transformer.rb', line 3

def params
  @params
end

Class Method Details

.input(name, type = nil, options = {}) ⇒ Object



25
26
27
28
29
30
# File 'lib/params_transformer/transformer.rb', line 25

def self.input(name, type = nil, options = {})
  @@input_definitions ||= {}
  array = @@input_definitions[self.name].present? ? @@input_definitions[self.name] : []
  array << [name, type, options]
  @@input_definitions[self.name] = array
end

.input_definitionsObject



32
33
34
# File 'lib/params_transformer/transformer.rb', line 32

def self.input_definitions
  @@input_definitions
end

Instance Method Details

#transformObject



12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/params_transformer/transformer.rb', line 12

def transform
  hash = {}
  inputs.each do |input|
    value = instance_variable_get("@#{input.variable_name}")

    # only set values to nil when they are intended to be nil
    next if value.nil? && (input.association? || params.keys.exclude?(input.name.to_s))

    hash[input.variable_name] = value
  end
  hash
end