Class: Qo::Destructurers::Destructurer
- Inherits:
-
Object
- Object
- Qo::Destructurers::Destructurer
- Defined in:
- lib/qo/destructurers/destructurer.rb
Overview
Classic destructuring. This gives great value to the names of a function's arguments, transforming the way blocks are normally yielded to. Take for example this function:
Proc.new { |name, age| ... }
The names of the arguments are name
and age
. Destructuring involves
using these names to extract the values of an object before the function
is called:
- Get the names of the arguments
- Map over those names to extract values from an object by sending them as method calls
- Call the function with the newly extracted values
It's highly suggested to read through the "Destructuring in Ruby" article here:
Instance Method Summary collapse
-
#argument_names ⇒ Array[Symbol]
Names of the function's arguments.
-
#call(target) ⇒ Any
Calls the destructurer to extract values from a target and call the function with those extracted values.
-
#destructure? ⇒ Boolean
Whether or not this method will destructure a passed object.
-
#destructure_values(target) ⇒ Array[Any]
Destructures values from a target object.
-
#initialize(destructure:, &function) ⇒ Qo::Destructurers::Destructurer
constructor
Creates a destructurer.
Constructor Details
#initialize(destructure:, &function) ⇒ Qo::Destructurers::Destructurer
Creates a destructurer
37 38 39 40 41 |
# File 'lib/qo/destructurers/destructurer.rb', line 37 def initialize(destructure:, &function) @destructure = destructure @function = function || IDENTITY @argument_names = argument_names end |
Instance Method Details
#argument_names ⇒ Array[Symbol]
Names of the function's arguments
80 81 82 |
# File 'lib/qo/destructurers/destructurer.rb', line 80 def argument_names @argument_names ||= @function.parameters.map(&:last) end |
#call(target) ⇒ Any
Calls the destructurer to extract values from a target and call the function with those extracted values.
51 52 53 54 55 |
# File 'lib/qo/destructurers/destructurer.rb', line 51 def call(target) destructured_arguments = destructure? ? destructure_values(target) : target @function.call(destructured_arguments) end |
#destructure? ⇒ Boolean
Whether or not this method will destructure a passed object
60 61 62 |
# File 'lib/qo/destructurers/destructurer.rb', line 60 def destructure? @destructure end |
#destructure_values(target) ⇒ Array[Any]
Destructures values from a target object
71 72 73 74 75 |
# File 'lib/qo/destructurers/destructurer.rb', line 71 def destructure_values(target) target.is_a?(::Hash) ? argument_names.map { |n| target[n] } : argument_names.map { |n| target.respond_to?(n) && target.public_send(n) } end |