Class: Module

Inherits:
Object show all
Defined in:
lib/rext/module/helpers.rb

Instance Method Summary collapse

Instance Method Details

#call_method(method, options = {}) ⇒ Object

Call method when conditions are met.

This method provides a simple means of utilizing method_missing, and should be used in most cases.

When using a regular expression with the :if option, all captures are passed to the handling method.

Examples

class Foo
  call_method :find_by, :if => /^find_by_(\w+)/
  def find_by attr, *args
    "finding by #{attr} with #{args.join(', ')}"
  end
end

foo = Foo.new
foo.find_by_name('bar') # => "finding by name with bar"

Options

:if   regexp or proc


48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/rext/module/helpers.rb', line 48

def call_method method, options = {}
  chainable {
    define_method :method_missing do |meth, *args|
      if options[:if].is_a?(Regexp) && meth.to_s =~ options[:if]
        send method, *($~.captures + args)
      elsif options[:if].respond_to?(:call) && options[:if].call(meth, *args)
        send method, *args
      else
        super
      end
    end
  }
end

#chainable(&block) ⇒ Object

Shortcut for including an anonymous module.



9
10
11
# File 'lib/rext/module/helpers.rb', line 9

def chainable &block
  include Module.new(&block)
end

#extendable(&block) ⇒ Object

Shortcut for extending with an anonymous module.



16
17
18
# File 'lib/rext/module/helpers.rb', line 16

def extendable &block
  extend Module.new(&block)
end

#setup(&block) ⇒ Object

Equivalent to defining self.included and instance evaluating the module passed.

Examples

def self.included mod
  mod.instance_eval do
    include InstanceMethods
  end
end

setup do 
  include InstanceMethods
end


79
80
81
82
83
# File 'lib/rext/module/helpers.rb', line 79

def setup &block
  meta_def :included do |mod|
    mod.instance_eval &block
  end
end