Class: Fondue::HashClass

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

Overview

A basic hash-centric class implementation. Extend it and specify a hash_attribute, to which all missing methods will be delegated to. If no hash attribute is specified, it is inferred from the class name Example:

class MyDataContainer < Fondue::HashClass
  hash_attribute :data
end

c = MyDataContainer.new(:data => {:foo => 'bar'})
c.map { |k,v| puts "#{k} => #{v}" }
#=> "foo => bar"
c[:foo]
#=> 'bar'
c.foo
#=> 'bar'

Direct Known Subclasses

Firefox::Addons, Firefox::Prefs

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ HashClass

Returns a new instance of HashClass.



18
19
20
21
22
23
# File 'lib/fondue/hash_class.rb', line 18

def initialize options = {}
  options.map do |k,v| 
    self.class.send(:attr_accessor,k.to_sym) unless respond_to?(:"#{k}=")
    send(:"#{k}=",v)
  end
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

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



25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/fondue/hash_class.rb', line 25

def method_missing name, *args, &block
  hash = instance_variable_get(self.class.get_hash_attribute)
  if hash.respond_to?(name)
    hash.send(name,*args)
  elsif hash.key?(name)
    hash[name]
  elsif hash.key?(name.to_s)
    hash[name.to_s]
  else
    super
  end
end

Class Method Details

.get_hash_attributeObject



44
45
46
47
48
49
50
# File 'lib/fondue/hash_class.rb', line 44

def get_hash_attribute
  if @hash_attribute and @hash_attribute != ''
    @hash_attribute
  else
    "@#{stringify(self.to_s)}"
  end
end

.hash_attribute(attr_name) ⇒ Object



40
41
42
# File 'lib/fondue/hash_class.rb', line 40

def hash_attribute attr_name
  @hash_attribute = "@#{attr_name}"
end

.stringify(klass) ⇒ Object



52
53
54
55
# File 'lib/fondue/hash_class.rb', line 52

def stringify klass
  string = klass.to_s.split('::').last
  string.gsub(/([A-Z][a-z]*)/,'_\1').gsub(/^_/,'').downcase
end