Class: UsesStoredProcedures::HashWithAttributes

Inherits:
Hash
  • Object
show all
Defined in:
lib/uses_stored_procedures/hash_with_attributes.rb

Overview

HashWithAttributes augments Hash with getters and setters on an as needed basis.

When ever an instance of HashWithAttributes is sent an accessor message, or a respond_to? message that matches a hash key for the first time, a setter and getter is created for that key which may be either a symbol or a string.

Examples:


h = HashWithAttributes.new
h[:one] = 1
h['two'] = 2
h.one = 3
h.two = 4
puts "One is #{h.one} and Two is #{h.two}"
# > One is 3 and Two is 4

Instance Method Summary collapse

Constructor Details

#initialize(hash_or_obj = nil) ⇒ HashWithAttributes

Create a new HashWithAttributes.

from another hash, or work like Hash where the object is the default for empty entries.

Parameters:

  • hash_or_obj (Object) (defaults to: nil)

    will initialize the hash



30
31
32
33
34
35
36
37
# File 'lib/uses_stored_procedures/hash_with_attributes.rb', line 30

def initialize(hash_or_obj = nil)
  if hash_or_obj && hash_or_obj.kind_of?(Hash)
    super()
    self.merge! hash_or_obj
  else
    super
  end
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

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



39
40
41
42
43
44
45
# File 'lib/uses_stored_procedures/hash_with_attributes.rb', line 39

def method_missing(name, *args, &block)
  if check_and_create_accessors(name)
    args.length > 0 ? send(name.to_s, args.first) : send(name.to_s)
  else
    super
  end
end

Instance Method Details

#respond_to?(symbol, include_private = false) ⇒ Boolean

Returns:

  • (Boolean)


47
48
49
# File 'lib/uses_stored_procedures/hash_with_attributes.rb', line 47

def respond_to?(symbol, include_private = false)
  super || check_and_create_accessors(symbol)
end