Class: SnakyHash::Extensions

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

Constructor Details

#initializeExtensions

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

Yields:

  • (value)

    block that will be called with a value to transform

Raises:



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



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

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

#resetHash

Reset the registry of extensions to an empty state



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



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