Class: SugarCube::Anonymous

Inherits:
Hash
  • Object
show all
Defined in:
lib/sugarcube-anonymous/anonymous.rb

Overview

A subclass of Hash that allows its keys to be accessed and assigned by method name. Useful to quickly mock objects. To that end, a NoMethodError is raised anytime the key doesn't exist (getter or setter)

You can convert an existing Hash or NSDictionary into a Anonymous using the constructor SugarCube::Anonymous[hash], or you can call to_object on a dictionary or hash.

Examples:

obj = {
  'first_name': 'Katsuyoshi',  # strings
  company: 'Ito Soft Design',  # and symbols are supported
}.to_object

obj.first_name
# => 'Katsuyoshi'
obj.company
# => 'Ito Soft Design'
obj.bla  # => raises NoMethodError
obj.bla = 'bla'  # => raises NoMethodError

Instance Method Summary collapse

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(symbol, *args) ⇒ Object



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/sugarcube-anonymous/anonymous.rb', line 24

def method_missing(symbol, *args)
  if args.size == 0
    key = symbol
    key = symbol.to_s unless self.include? key
    if self.include?(key)
      self[key] = self[key].to_object
      return self[key]
    end
  elsif args.size == 1 && /(.*)=$/ =~ symbol.to_s
    key = $1.to_sym
    key = key.to_s unless self.include? key
    if self.include?(key)
      return self[key] = args.first.to_object
    end
  end
  return super
end

Instance Method Details

#anonymous_eachObject

replace enumerable methods



47
# File 'lib/sugarcube-anonymous/anonymous.rb', line 47

alias :anonymous_each :each

#eachObject



49
50
51
# File 'lib/sugarcube-anonymous/anonymous.rb', line 49

def each
  anonymous_each {|k,v| yield k, v.to_object}
end

#to_objectObject



42
43
44
# File 'lib/sugarcube-anonymous/anonymous.rb', line 42

def to_object
  self
end