Module: StickyBlox::ClassMethods

Defined in:
lib/sticky_blox/behavior.rb

Instance Method Summary collapse

Instance Method Details

#my_meta_classObject



25
26
27
# File 'lib/sticky_blox/behavior.rb', line 25

def my_meta_class
  class << self; self; end
end

#stick(name, replace = false, &block) ⇒ Object



77
78
79
80
81
82
83
84
85
86
87
88
89
90
# File 'lib/sticky_blox/behavior.rb', line 77

def stick(name, replace=false, &block)
  my_methods = stuck_methods
  if replace && my_methods.has_key?(name)
    my_methods.delete(name)
  end
  (my_methods[name] ||= BindingArray.new) << block

  my_methods = my_methods[name]
  self.class.class_eval do
    define_method name do
      my_methods
    end
  end
end

#stick_to(binding) ⇒ Object

Defines methods on the class identified by “binding” for each method in @stuck_methods that will call the block associated with that method name, passing any arguments that are defined at runtime



40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/sticky_blox/behavior.rb', line 40

def stick_to( binding )
  my_meta_class.instance_eval do
    clz = self
    @stuck_methods.each_pair do |method_name, binding_array|
      binding.class_eval do
        define_method method_name do | *args |
          binding_array.bind(self).call(*args)
        end
      end
    end
  end
end

#stuck_methodsObject



29
30
31
32
33
34
# File 'lib/sticky_blox/behavior.rb', line 29

def stuck_methods
  my_meta_class.instance_eval do
    @stuck_methods ||= {}
    @stuck_methods
  end
end

#unstick_all_from(binding, ignore_errors = true) ⇒ Object



73
74
75
# File 'lib/sticky_blox/behavior.rb', line 73

def unstick_all_from( binding, ignore_errors=true )
  unstick_from( binding => my_meta_class.instance_variable_get("@stuck_methods").keys, :ignore_errors => ignore_errors )
end

#unstick_from(options = {}) ⇒ Object



53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# File 'lib/sticky_blox/behavior.rb', line 53

def unstick_from( options={} )
  ignore_errors = options.delete(:ignore_errors)
  options.each_pair do |binding, method_names|
    method_names = [method_names].flatten
    method_names.each do |method_name|
      binding.class_eval do
        begin
          # remove_method removes it from a specific class, but not its parent
          # Do we want to use undef_method which will remove it from the whole
          # inheritance chain?
          remove_method method_name
        rescue NoMethodError => e
          # unless told otherwise, ignore the error -- if we don't respond to the method, no harm done.
          raise e unless ignore_errors
        end
      end if binding.instance_methods.detect{|e| e.to_s == method_name.to_s}
    end
  end
end