Class: Clafamatt::MacroModule
- Inherits:
-
Module
- Object
- Module
- Clafamatt::MacroModule
- Defined in:
- lib/clafamatt.rb
Overview
This might be better named SingletonModule. A MacroModule acts as a container for singleton methods attached to a given class or module. This way we can share singleton methods across arbitrary classes and modules.
MacroModule also ensures that the class being "decorated" with a MacroModule of its own will also inherit all of its ancestors' macros.
Instance Attribute Summary collapse
-
#decorated_class ⇒ Object
readonly
Returns the value of attribute decorated_class.
Class Method Summary collapse
Instance Method Summary collapse
- #==(other) ⇒ Object
- #copy_ancestor_macro_modules! ⇒ Object
- #extend_class! ⇒ Object
-
#initialize(decorated_class) ⇒ MacroModule
constructor
A new instance of MacroModule.
- #inspect ⇒ Object
Constructor Details
#initialize(decorated_class) ⇒ MacroModule
Returns a new instance of MacroModule.
66 67 68 |
# File 'lib/clafamatt.rb', line 66 def initialize(decorated_class) @decorated_class = decorated_class end |
Instance Attribute Details
#decorated_class ⇒ Object (readonly)
Returns the value of attribute decorated_class.
91 92 93 |
# File 'lib/clafamatt.rb', line 91 def decorated_class @decorated_class end |
Class Method Details
.find_all_for(klass) ⇒ Object
62 63 64 65 |
# File 'lib/clafamatt.rb', line 62 def self.find_all_for(klass) klass_singleton = class << klass; self; end klass_singleton.ancestors.grep(MacroModule) end |
.find_or_create_for(klass) ⇒ Object
51 52 53 54 55 56 57 58 59 60 61 |
# File 'lib/clafamatt.rb', line 51 def self.find_or_create_for(klass) mod = self.new(klass) extend_klass = lambda do mod.extend_class! mod end klass_singleton = class << klass; self; end klass_singleton.ancestors.find(extend_klass){|a| a == mod } end |
Instance Method Details
#==(other) ⇒ Object
70 71 72 |
# File 'lib/clafamatt.rb', line 70 def ==(other) self.class == other.class && self.decorated_class == other.decorated_class end |
#copy_ancestor_macro_modules! ⇒ Object
78 79 80 81 82 83 84 85 |
# File 'lib/clafamatt.rb', line 78 def copy_ancestor_macro_modules! @decorated_class.ancestors.each do |ancestor| macro_modules = self.class.find_all_for(ancestor) macro_modules.each do |mm| @decorated_class.extend(mm) end end end |
#extend_class! ⇒ Object
87 88 89 90 |
# File 'lib/clafamatt.rb', line 87 def extend_class! copy_ancestor_macro_modules! @decorated_class.extend(self) end |
#inspect ⇒ Object
74 75 76 |
# File 'lib/clafamatt.rb', line 74 def inspect "#<Clafamatt::MacroModule:#{@decorated_class}:(#{self.instance_methods(false).join(", ")})>" end |