Module: ParamParam::Actions
- Defined in:
- lib/param_param.rb
Overview
Actions definitions.
Instance Method Summary collapse
-
#all_of ⇒ Object
It return lambda that allows defining a chain of rules that will be applied one by one to value processed by a previous rule.
-
#any ⇒ Object
Returns lambda { |option| … }.
-
#define ⇒ Object
Defines pipelines and binds them to symbols.
-
#optionize(value) ⇒ Object
Converts provided value to
Optiomist::Some
.
Instance Method Details
#all_of ⇒ Object
It return lambda that allows defining a chain of rules that will be applied one by one to value processed by a previous rule.
Returns:
lambda { |fns, option| ... }
If some rule fails the chain is broken and value stops being processed.
67 68 69 70 71 |
# File 'lib/param_param.rb', line 67 def all_of lambda { |fns, option| fns.reduce(Success.new(option)) { |result, fn| result.failure? ? result : fn.call(result.value) } }.curry end |
#any ⇒ Object
Returns
lambda { |option| ... }.
Always succeeds with the provided option
.
77 78 79 |
# File 'lib/param_param.rb', line 77 def any ->(option) { Success.new(option) } end |
#define ⇒ Object
Defines pipelines and binds them to symbols. Pipelines are used to process parameters provided in a form of a hash. Each pipeline is defined for a key and processes a value related to that key in provided parameters.
lambda { |rules, params| ... }
The lambda 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 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 second hash
Each action needs to be a lambda taking Optiomist
as the only or the last parameter and returning either:
-
ParamParam::Success
with processed option -
ParamParam::Failure
with an error
46 47 48 49 50 51 52 53 54 55 56 57 58 59 |
# File 'lib/param_param.rb', line 46 def define lambda { |rules, params| results = rules.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] }.curry end |
#optionize(value) ⇒ Object
Converts provided value to Optiomist::Some
. If the value is already Optiomist::Some
or Optiomist::None
returns it untouched.
24 25 26 27 28 29 30 |
# File 'lib/param_param.rb', line 24 def optionize(value) if value.is_a?(Optiomist::Some) || value.is_a?(Optiomist::None) value else Optiomist.some(value) end end |