Class: Object
- Inherits:
- BasicObject
- Defined in:
- lib/clean-annotations/class_callbacks.rb,
lib/clean-annotations/method_attr.rb,
lib/clean-annotations/class_attribute.rb
Overview
Rails style callbacks
Instance Method Summary collapse
- #class_attribute(name) ⇒ Object
- #define_callback(name) ⇒ Object
- #method_attr(name = nil, &block) ⇒ Object
- #run_callback(name, *args) ⇒ Object
Instance Method Details
#class_attribute(name) ⇒ Object
30 31 32 |
# File 'lib/clean-annotations/class_attribute.rb', line 30 def class_attribute name self.class.send(name) end |
#define_callback(name) ⇒ Object
4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
# File 'lib/clean-annotations/class_callbacks.rb', line 4 def define_callback name ivar = "@class_callbacks_#{name}" unless is_a?(Class) || is_a?(Module) raise ArgumentError, 'define_callback Can only be defined in a class or a module' end define_singleton_method(name) do |method_name=nil, &block| ref = caller[0].split(':in ').first self.instance_variable_set(ivar, {}) unless instance_variable_defined?(ivar) self.instance_variable_get(ivar)[ref] = method_name || block end end |
#method_attr(name = nil, &block) ⇒ Object
35 36 37 38 39 40 41 42 43 44 45 46 47 |
# File 'lib/clean-annotations/method_attr.rb', line 35 def method_attr name=nil, &block if respond_to?(:const_missing) && respond_to?(:ancestors) if name.nil? return MethodAttributes.get(self) || {} end MethodAttributes.define self, name, &block else # instance base = MethodAttributes.get(self.class) name ? base[name] : base end end |
#run_callback(name, *args) ⇒ Object
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
# File 'lib/clean-annotations/class_callbacks.rb', line 19 def run_callback name, *args ivar = "@class_callbacks_#{name}" list = is_a?(Class) || is_a?(Module) ? ancestors : self.class.ancestors list = list.slice 0, list.index(Object) if list.index(Object) list.reverse.each do |klass| if klass.instance_variable_defined?(ivar) mlist = klass.instance_variable_get(ivar).values mlist.each do |m| if m.is_a?(Symbol) send m, *args else instance_exec *args, &m end end end end end |