Class: SpecialObject
- Inherits:
-
YAMLParser
- Object
- YAMLParser
- SpecialObject
- Defined in:
- lib/yaml-parser.rb
Instance Method Summary collapse
-
#initialize(hash) ⇒ SpecialObject
constructor
Save the input object in an instance variable.
-
#method_missing(meth_sym, *args, &block) ⇒ Object
Catch missing method errors here and try to build the ones we need.
-
#respond_to?(meth_sym, private_method = false) ⇒ Boolean
Make sure we respond to the new methods we are creating.
Methods inherited from YAMLParser
Constructor Details
#initialize(hash) ⇒ SpecialObject
Save the input object in an instance variable
30 31 32 |
# File 'lib/yaml-parser.rb', line 30 def initialize(hash) @object_hash = hash end |
Dynamic Method Handling
This class handles dynamic methods through the method_missing method
#method_missing(meth_sym, *args, &block) ⇒ Object
Catch missing method errors here and try to build the ones we need
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 |
# File 'lib/yaml-parser.rb', line 35 def method_missing(meth_sym, *args, &block) # If the object that has been passed in is an array, we have to treat it differently if @object_hash.class == Array # We only need to cover the first and last methods for the arrays, so we are going to # check what the user called and act accordingly if meth_sym.to_s == "first" # If the array.first call returns a string (as opposed to other data types) then that is the answer we want to return # Otherwise return a ew SpecialObject with the modified object as the argument @object_hash[0].class == String ? @object_hash[0] : SpecialObject.new(@object_hash[0]) else @object_hash[-1].class == String ? @object_hash[-1] : SpecialObject.new(@object_hash[-1]) end # If the user tries to access the hash with the [] operator, let them, and just return a hash elsif meth_sym.to_s == "[]" @object_hash[*args] # If the hash has a key that is the same as the method they called, return the value elsif @object_hash[meth_sym.to_s] # If the key has a value that is a string, that is the last step in the chain. Otherwise, return a new special object @object_hash[meth_sym.to_s].class == String ? @object_hash[meth_sym.to_s] : SpecialObject.new(@object_hash["#{meth_sym}"]) # If none of the above is true, throw a no method error else super end end |
Instance Method Details
#respond_to?(meth_sym, private_method = false) ⇒ Boolean
Make sure we respond to the new methods we are creating
68 69 70 |
# File 'lib/yaml-parser.rb', line 68 def respond_to?(meth_sym, private_method = false) true end |