Module: Attic::InstanceMethods
- Defined in:
- lib/attic/instance_methods.rb
Overview
Adds a few methods for object instances to access the attic variables of their class.
Instance Method Summary collapse
- #attic ⇒ Object
-
#attic? ⇒ Boolean
A quick way to check if this object instance already has a dedicated singleton class.
- #attic_variable?(name) ⇒ Boolean
- #attic_variable_get(name) ⇒ Object
- #attic_variable_set(name, val) ⇒ Object
- #attic_variables ⇒ Object
Instance Method Details
#attic ⇒ Object
10 11 12 13 14 15 16 17 |
# File 'lib/attic/instance_methods.rb', line 10 def attic raise NoSingletonError, self, caller unless attic? singleton_class rescue TypeError NoSingletonError.add_member self end |
#attic? ⇒ Boolean
A quick way to check if this object instance already has a dedicated singleton class. We like to know this upfront because this is where our attic variables are to be stored.
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
# File 'lib/attic/instance_methods.rb', line 22 def attic? return false if NoSingletonError.member? self # NOTE: Calling this on an object for the first time lazily # creates a singleton class for itself. Another way of doing # the same thing is to attempt defining a singleton method # for the object. In either case, objects that cannot have # cannot have a dedicated singleton class (e.g. nil, true, # false) will raise a TypeError. We rescue this and add the # object to the NoSingletonError list so we don't keep # trying to access its singleton class over and over. # # NOTE 2: Module#singleton_class? is only available for # modules and classes (which are also modules); it is not # available for instances of classes. # !singleton_class.nil? rescue TypeError # Remember for next time. NoSingletonError.add_member self false end |
#attic_variable?(name) ⇒ Boolean
50 51 52 |
# File 'lib/attic/instance_methods.rb', line 50 def attic_variable?(name) self.class.attic_variable? name end |
#attic_variable_get(name) ⇒ Object
60 61 62 |
# File 'lib/attic/instance_methods.rb', line 60 def attic_variable_get(name) attic.instance_variable_get("@___attic_#{name}") end |
#attic_variable_set(name, val) ⇒ Object
54 55 56 57 58 |
# File 'lib/attic/instance_methods.rb', line 54 def attic_variable_set(name, val) raise FrozenError, self, caller if frozen? attic_variables << name unless attic_variable? name attic.instance_variable_set("@___attic_#{name}", val) end |
#attic_variables ⇒ Object
46 47 48 |
# File 'lib/attic/instance_methods.rb', line 46 def attic_variables self.class.attic_variables end |