Class: Idolent::LazyHash

Inherits:
Object
  • Object
show all
Defined in:
lib/idolent.rb

Instance Method Summary collapse

Constructor Details

#initialize(hash = {}, clazz) ⇒ LazyHash

Returns a new instance of LazyHash.



62
63
64
65
66
67
# File 'lib/idolent.rb', line 62

def initialize(hash = {}, clazz)
  raise "class #{clazz} must have a load method" unless clazz.respond_to?(:load)
  raise "class #{clazz} must have a dump method" unless clazz.respond_to?(:dump)
  @hash = hash
  @clazz = clazz
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method, *args, &block) ⇒ Object



69
70
71
72
73
74
75
76
77
78
79
80
# File 'lib/idolent.rb', line 69

def method_missing(method, *args, &block)
  case method
    when :each, :each_pair
      @hash.send(method) { |k,v| yield k, @clazz.load(v) }
    when :each_value
      @hash.send(method) { |v| yield @clazz.load(v) }
    when :fetch
      @clazz.load(@hash.send(method, *args))
    else
      @hash.send(method, *args, &block)
  end
end

Instance Method Details

#[](key) ⇒ Object



82
83
84
85
86
87
88
89
90
# File 'lib/idolent.rb', line 82

def [](key)
  if @hash.has_key?(key.to_s)
    @clazz.load(@hash[key.to_s])
  elsif @hash.has_key?(key.to_sym)
    @clazz.load(@hash[key.to_sym])
  else
    nil
  end
end

#[]=(key, value) ⇒ Object



92
93
94
95
96
97
98
99
100
# File 'lib/idolent.rb', line 92

def []=(key, value)
  if @hash.has_key?(key.to_s)
    @hash[key.to_s] = @clazz.dump(value)
  elsif @hash.has_key?(key.to_sym)
    @hash[key.to_sym] = @clazz.dump(value)
  else
    @hash[key] = @clazz.dump(value)
  end
end

#valuesObject



102
103
104
# File 'lib/idolent.rb', line 102

def values
  @hash.values.collect { |v| @clazz.new(v) }
end