Class: SnakyHash::Extensions — Documentation by YARD 0.9.43

# Class: SnakyHash::Extensions

Inherits:
  Object
  - Object
  - SnakyHash::Extensions
  show all

Defined in:
  lib/snaky_hash/extensions.rb

## Overview

Manages extensions that can modify values in a chain of transformations

#### Examples:

#####

Adding and running an extension

    extensions = Extensions.new
    extensions.add(:upcase) { |value| value.to_s.upcase }
    extensions.run("hello") #=> "HELLO"

## Instance Method Summary collapse

- #add(name) {|value| ... } ⇒ Proc

  Adds a new extension with the given name.

- #has?(name) ⇒ Boolean

  Checks if an extension with the given name exists.

- #initialize ⇒ Extensions constructor

  Initializes a new Extensions instance with an empty extensions registry.

- #reset ⇒ Hash

  Reset the registry of extensions to an empty state.

- #run(value) ⇒ Object

  Runs all registered extensions in sequence on the given value.

## Constructor Details

### #initialize ⇒ `Extensions`

Initializes a new Extensions instance with an empty extensions registry

    13
    14
    15
    # File 'lib/snaky_hash/extensions.rb', line 13

    def initialize
      reset
    end

## Instance Method Details

### #add(name) {|value| ... } ⇒ `Proc`

Adds a new extension with the given name

Parameters:

- name (`String`, `Symbol`) —

  the name of the extension

Yields:

- (`value`) —

  block that will be called with a value to transform

Returns:

- (`Proc`) —

  the added extension block

Raises:

- (`SnakyHash::Error`) —

  if an extension with the given name already exists

    30
    31
    32
    33
    34
    35
    36
    # File 'lib/snaky_hash/extensions.rb', line 30

    def add(name, &block)
      if has?(name)
        raise Error, "Extension already defined named '#{name}'"
      end

      @extensions[name.to_sym] = block
    end

### #has?(name) ⇒ `Boolean`

Checks if an extension with the given name exists

Parameters:

- name (`String`, `Symbol`) —

  the name of the extension to check

Returns:

- (`Boolean`) —

  true if the extension exists, false otherwise

    42
    43
    44
    # File 'lib/snaky_hash/extensions.rb', line 42

    def has?(name)
      @extensions.key?(name.to_sym)
    end

### #reset ⇒ `Hash`

Reset the registry of extensions to an empty state

Returns:

- (`Hash`) —

  an empty hash of extensions

    20
    21
    22
    # File 'lib/snaky_hash/extensions.rb', line 20

    def reset
      @extensions = {}
    end

### #run(value) ⇒ `Object`

Runs all registered extensions in sequence on the given value

Parameters:

- value (`Object`) —

  the value to transform through all extensions

Returns:

- (`Object`) —

  the final transformed value after running all extensions

    50
    51
    52
    53
    54
    55
    # File 'lib/snaky_hash/extensions.rb', line 50

    def run(value)
      @extensions.each_value do |block|
        value = block.call(value)
      end
      value
    end