Class: Rash

Inherits:
Object show all
Defined in:
lib/epitools/rash.rb

Overview

A Regex-queryable Hash.

Usage:

greeting = Rash.new( /^Mr./ => "Hello sir!", /^Mrs./ => "Evening, madame." )
greeting["Mr. Steve Austin"] #=> "Hello sir!"
greeting["Mrs. Steve Austin"] #=> "Evening, madame."

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(initial = {}) ⇒ Rash


14
15
16
17
18
19
20
21
22
23
# File 'lib/epitools/rash.rb', line 14

def initialize(initial={})
  @hash           = {}
  @regexes        = []
  @ranges         = []
  @regex_counts   = Hash.new(0)
  @optimize_every = 500
  @lookups        = 0

  update(initial)
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(*args, &block) ⇒ Object


91
92
93
# File 'lib/epitools/rash.rb', line 91

def method_missing(*args, &block)
  @hash.send(*args, &block)
end

Instance Attribute Details

#optimize_everyObject

Returns the value of attribute optimize_every


12
13
14
# File 'lib/epitools/rash.rb', line 12

def optimize_every
  @optimize_every
end

Instance Method Details

#[](key) ⇒ Object

Return the first thing that matches the key.


46
47
48
# File 'lib/epitools/rash.rb', line 46

def [](key)
  all(key).first
end

#[]=(key, value) ⇒ Object


32
33
34
35
36
37
38
39
40
41
# File 'lib/epitools/rash.rb', line 32

def []=(key, value)
  case key
  when Regexp
    #key = normalize_regex(key)  # this used to just do: /#{regexp}/
    @regexes << key
  when Range
    @ranges << key
  end
  @hash[key] = value
end

#all(query) ⇒ Object

Return everything that matches the query.


53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
# File 'lib/epitools/rash.rb', line 53

def all(query)
  return to_enum(:all, query) unless block_given?

  if @hash.include? query
    yield @hash[query]
    return
  end

  case query
  when String
    optimize_if_necessary!
    @regexes.each do |regex|
      if match = regex.match(query)
        @regex_counts[regex] += 1
        value = @hash[regex]
        if value.responds_to? :call
          yield value.call(match)
        else
          yield value
        end
      end
    end

  when Integer
    @ranges.each do |range|
      yield @hash[range] if range.include? query
    end

  when Regexp
    # TODO: this doesn't seem very useful. should I ditch it? let me know!
    @hash.each do |key,val|
      yield val if key.is_a? String and query =~ key
    end

  end

end

#update(other) ⇒ Object


25
26
27
28
29
30
# File 'lib/epitools/rash.rb', line 25

def update(other)
  for key, value in other
    self[key] = value
  end
  self
end