Class: Sparrow::Strategies::TransformParams

Inherits:
Object
  • Object
show all
Defined in:
lib/sparrow/strategies/transform_params.rb

Overview

Core class to trigger the conversion

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(key_transformation_strategy_buzzword, options = {}) ⇒ TransformParams

Create a new TransformParams instance

Parameters:

  • key_transformation_strategy_buzzword (String)

    the strategy buzzword stating how to transform. Must be either ‘camelize’ or ‘underscore’

  • options (Hash) (defaults to: {})

    options for the key transformation strategy



30
31
32
33
34
35
# File 'lib/sparrow/strategies/transform_params.rb', line 30

def initialize(key_transformation_strategy_buzzword, options = {})
  self.options                     = options
  key_transformation_strategy      = create_key_transformation_strategy(
  key_transformation_strategy_buzzword)
  self.key_transformation_strategy = key_transformation_strategy
end

Instance Attribute Details

#key_transformation_strategyKeyTransformation

the strategy stating how to convert the JSON

Returns:

See Also:



14
15
16
# File 'lib/sparrow/strategies/transform_params.rb', line 14

def key_transformation_strategy
  @key_transformation_strategy
end

#optionsObject

Key Transformation Strategy options. Possible values differ by the specific strategy. E.g. for CamelizeKey options may be the strategy and camlize_uppercase_params

See Also:

  • KeyTransformationStrategy::CamelizeKey
  • KeyTransformationStrategy::UnderscoreKey


22
23
24
# File 'lib/sparrow/strategies/transform_params.rb', line 22

def options
  @options
end

Instance Method Details

#transform(collection_or_hash) ⇒ Array|Hash

Do the transformation

Parameters:

  • collection_or_hash (Array|Hash)

    the object to be transformed if it is an Array each object inside of it will be transformed, i.e. each Hash’s keys if it is a Hash each key will be transformed. Recursively.

Returns:

  • (Array|Hash)

    the transformed input



44
45
46
47
48
49
50
51
52
53
# File 'lib/sparrow/strategies/transform_params.rb', line 44

def transform(collection_or_hash)
  case collection_or_hash
    when Array
      collection_or_hash.map { |element| transform(element) }
    when Hash
      collection_or_hash.deep_transform_keys do |key|
        key_transformation_strategy.transform_key(key)
      end
  end
end