Class: HashFilter

Inherits:
Object
  • Object
show all
Defined in:
lib/hash_filter.rb,
lib/hash_filter/version.rb,
lib/hash_filter/operation.rb,
lib/hash_filter/operation/delete.rb,
lib/hash_filter/operation/rename.rb

Overview

Easy hash filtering via simple operations

See Also:

  • README

Defined Under Namespace

Classes: Operation

Constant Summary collapse

VERSION =
"0.1.1"

Instance Method Summary collapse

Constructor Details

#initialize {|HashFilter| ... } ⇒ HashFilter

Initialize a hash filter

Examples:

filter = HashFilter.new do
  rename /(.*?)\.htm$/, '\1.html'
  delete /\.(jpg|gif)$/
end

filter.delete /\.png$/

filter.apply(some_hash)

Yields:

  • (HashFilter)

    instance evals self if a block is provided



28
29
30
31
32
# File 'lib/hash_filter.rb', line 28

def initialize(&block)
  @keeps      = []
  @operations = []
  instance_eval(&block) if block
end

Instance Method Details

#apply(hash) ⇒ Object

Apply this filter to hash

Parameters:

  • hash (Hash)

    hash (hash-like) to filter



86
87
88
# File 'lib/hash_filter.rb', line 86

def apply(hash)
  apply_operations(@operations, hash.dup)
end

#delete(key) ⇒ Object

Delete a key

Examples:

remove_images = HashFilter.new do
  delete /\.jpg$/
  delete /\.png$/
  delete /\.gif$/
end

Parameters:

  • key (Regexp, String)

    key to delete



57
58
59
# File 'lib/hash_filter.rb', line 57

def delete(key)
  operation Operation::Delete, key
end

#inject(filter) ⇒ Object

Combine other filters

Parameters:



64
65
66
67
# File 'lib/hash_filter.rb', line 64

def inject(filter)
  @keeps.concat filter.keeps
  @operations.concat filter.operations
end

#keep(key) ⇒ Object

Keep given key

Examples:

# Delete everything but keep GIFs
HashFilter.new do
  keep /\.gif$/
  delete /.*/
end

Parameters:

  • key (Regexp, String)

    key to keep



79
80
81
# File 'lib/hash_filter.rb', line 79

def keep(key)
  @keeps << key
end

#operation(class_name, *args) ⇒ Object

Add a custom operation

Examples:

class SwapKeyValue < HashFilter::Operation
  def execute(hash, key)
    value = hash.delete(key)
    hash[value] = key
  end
end

HashFilter.new do
  operation SwapKeyValue
end

Parameters:



105
106
107
# File 'lib/hash_filter.rb', line 105

def operation(class_name, *args)
  @operations << class_name.new(*args)
end

#rename(from, to) ⇒ Object

Rename a key

Examples:

HashFilter.new do
  rename /(.*?)\.htm$/, '\1.html'
end

Parameters:

  • from (Regexp, String)

    rename source

  • to (String)

    rename target



43
44
45
# File 'lib/hash_filter.rb', line 43

def rename(from, to)
  operation Operation::Rename, from, to
end