Class: ParamParam::Actions

Inherits:
Object
  • Object
show all
Defined in:
lib/param_param/actions.rb

Overview

Defines actions to process hash values.

An action is a lambda function assigned to a key. When a hash with values is provied, a value related to a key of the same name as the one the action is assigned to, processes the value.

An action needs to be a lambda taking Optiomist option as parameter and returning either:

  • ParamParam::Success with processed option

  • ParamParam::Failure with an error

Example:

actions = Actions.new(
  key: lambda { |option| option.some? ? Success.new(process(option.value)) : Failure.new(:missing) },
  ...
)

Instance Method Summary collapse

Constructor Details

#initialize(actions) ⇒ Actions

Returns a new instance of Actions.



19
20
21
# File 'lib/param_param/actions.rb', line 19

def initialize(actions)
  @actions = actions
end

Instance Method Details

#call(params) ⇒ Object

It takes a hash and processes values related to a key by an action assigned to the same key.

It returns two hashes:

  • if a value related to a key can be procesed by an action, the result is bound to the key and added to the first params hash

  • if a value related to a key can’t be processed by an action, the error is bound to the key and added to the last errors hash



30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/param_param/actions.rb', line 30

def call(params)
  results = actions.to_h do |key, fn|
    option = params.key?(key) ? optionize(params[key]) : Optiomist.none
    [key, fn.call(option)]
  end

  errors = results.select { |_, result| result.failure? }
                  .transform_values(&:error)
  params = results.select { |_, result| result.success? && result.value.some? }
                  .transform_values { |result| result.value.value }
  [params, errors]
end