Class: Qo::Destructurers::Destructurer

Inherits:
Object
  • Object
show all
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:

  1. Get the names of the arguments
  2. Map over those names to extract values from an object by sending them as method calls
  3. 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

Constructor Details

#initialize(destructure:, &function) ⇒ Qo::Destructurers::Destructurer

Creates a destructurer

Parameters:

  • destructure: (Boolean)

    Whether or not to destructure an object before calling a function

  • &function (Proc)

    Associated function to be called

Since:

  • 1.0.0



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_namesArray[Symbol]

Names of the function's arguments

Returns:

  • (Array[Symbol])

Since:

  • 1.0.0



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.

Parameters:

  • target (Any)

    Target to extract values from

Returns:

  • (Any)

    Return of the given function

Since:

  • 1.0.0



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

Returns:

  • (Boolean)

Since:

  • 1.0.0



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

Parameters:

  • target (Any)

    Object to extract values from

Returns:

  • (Array[Any])

    Extracted values

Since:

  • 1.0.0



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