Skip to content

Instantly share code, notes, and snippets.

@JuanitoFatas
Created June 30, 2014 07:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JuanitoFatas/0616985c2ae186023c80 to your computer and use it in GitHub Desktop.
Save JuanitoFatas/0616985c2ae186023c80 to your computer and use it in GitHub Desktop.
Forwardable and SingleForwardable (without comments) from https://github.com/ruby/ruby/blob/trunk/lib/forwardable.rb
module Forwardable
FORWARDABLE_VERSION = "1.1.0"
FILE_REGEXP = %r"#{Regexp.quote(__FILE__)}"
@debug = nil
class << self
attr_accessor :debug
end
def instance_delegate(hash)
hash.each{ |methods, accessor|
methods = [methods] unless methods.respond_to?(:each)
methods.each{ |method|
def_instance_delegator(accessor, method)
}
}
end
def def_instance_delegators(accessor, *methods)
methods.delete("__send__")
methods.delete("__id__")
for method in methods
def_instance_delegator(accessor, method)
end
end
def def_instance_delegator(accessor, method, ali = method)
line_no = __LINE__; str = %{
def #{ali}(*args, &block)
begin
#{accessor}.__send__(:#{method}, *args, &block)
rescue Exception
$@.delete_if{|s| Forwardable::FILE_REGEXP =~ s} unless Forwardable::debug
::Kernel::raise
end
end
}
begin
module_eval(str, __FILE__, line_no)
rescue
instance_eval(str, __FILE__, line_no)
end
end
alias delegate instance_delegate
alias def_delegators def_instance_delegators
alias def_delegator def_instance_delegator
end
module SingleForwardable
def single_delegate(hash)
hash.each{ |methods, accessor|
methods = [methods] unless methods.respond_to?(:each)
methods.each{ |method|
def_single_delegator(accessor, method)
}
}
end
def def_single_delegators(accessor, *methods)
methods.delete("__send__")
methods.delete("__id__")
for method in methods
def_single_delegator(accessor, method)
end
end
def def_single_delegator(accessor, method, ali = method)
str = %{
def #{ali}(*args, &block)
begin
#{accessor}.__send__(:#{method}, *args, &block)
rescue Exception
$@.delete_if{|s| Forwardable::FILE_REGEXP =~ s} unless Forwardable::debug
::Kernel::raise
end
end
}
instance_eval(str, __FILE__, __LINE__)
end
alias delegate single_delegate
alias def_delegators def_single_delegators
alias def_delegator def_single_delegator
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment