Module: Attic::ClassMethods
- Defined in:
- lib/attic/class_methods.rb
Overview
Adds a few methods for accessing the metaclass of an object. We do this with great caution since the Object class is as global as it gets in Ruby.
Instance Attribute Summary collapse
-
#attic_variables ⇒ Object
readonly
A list of all the attic variables defined for this class.
Instance Method Summary collapse
- #attic(name = nil) ⇒ Object
-
#attic? ⇒ Boolean
A quick way to check if the current object already has a dedicated singleton class.
- #attic_variable?(name) ⇒ Boolean
- #attic_variable_get(name) ⇒ Object
- #attic_variable_set(name, val) ⇒ Object
Instance Attribute Details
#attic_variables ⇒ Object (readonly)
A list of all the attic variables defined for this class.
10 11 12 |
# File 'lib/attic/class_methods.rb', line 10 def attic_variables @attic_variables end |
Instance Method Details
#attic(name = nil) ⇒ Object
34 35 36 37 38 39 40 41 42 43 44 45 |
# File 'lib/attic/class_methods.rb', line 34 def attic(name=nil) return singleton_class if name.nil? name = name.normalize self.attic_variables << name unless attic_variable? name safe_name = "@_attic_#{name}" instance_variable_set(safe_name, name) rescue TypeError => e raise NoSingletonError, name, caller end |
#attic? ⇒ Boolean
A quick way to check if the current object already has a dedicated singleton class. We want to know this because this is where our attic variables will be stored.
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
# File 'lib/attic/class_methods.rb', line 15 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. !singleton_class.nil? rescue TypeError # Remember for next time. NoSingletonError.add_member self false end |
#attic_variable?(name) ⇒ Boolean
47 48 49 |
# File 'lib/attic/class_methods.rb', line 47 def attic_variable?(name) attic_variables.include? name.normalize end |
#attic_variable_get(name) ⇒ Object
58 59 60 |
# File 'lib/attic/class_methods.rb', line 58 def attic_variable_get(name) instance_variable_get("@_attic_#{name}") end |
#attic_variable_set(name, val) ⇒ Object
51 52 53 54 55 56 |
# File 'lib/attic/class_methods.rb', line 51 def attic_variable_set(name, val) unless attic_variable? name attic_variables << name.normalize end attic.instance_variable_set("@_attic_#{name}", val) end |