Class: Xhive::Hashy

Inherits:
Hash
  • Object
show all
Defined in:
lib/xhive/hashy.rb

Overview

Adds the ability to get/set an attribute using the dot operator

Examples

a = Hashy.new
a.foo # => nil
a.foo = 'bar'
a.foo # => 'bar'

a = Hashy.new(:foo => 'bar')
a.foo # => 'bar'
a.duu # => nil

Direct Known Subclasses

AnonymousUser

Instance Method Summary collapse

Constructor Details

#initialize(attrs = {}) ⇒ Hashy

Public: initializer

attrs - The Hash containing the initial elements (default: {})

Returns an instance of Hashy



21
22
23
24
# File 'lib/xhive/hashy.rb', line 21

def initialize(attrs={})
  super
  attrs.each {|k,v| self[k.to_sym] = v }
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(sym, *args, &block) ⇒ Object (private)



28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/xhive/hashy.rb', line 28

def method_missing(sym, *args, &block)
  # If I receive a method with the form 'foo='
  if sym.to_s =~ /=/
    attr = sym.to_s.scan(/(\w*)=/)
    self[attr[0][0].to_sym] = args[0] unless attr.empty?
  elsif sym.to_s =~ /^.*\?$/
    attr = sym.to_s.scan(/(\w*)\?/)
    self.fetch(attr[0][0].to_sym, false) ? true : false
  else
    # This should be the standard behavior with []
    self.fetch(sym, nil)
  end
end