Skip to content

Instantly share code, notes, and snippets.

@nowherekai
Created January 8, 2016 08:20
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 nowherekai/f8ef404ca8c7224d2aaa to your computer and use it in GitHub Desktop.
Save nowherekai/f8ef404ca8c7224d2aaa to your computer and use it in GitHub Desktop.
#simple delegate, can not use in production
class Module
def delegate(*methods)
options = methods.pop
unless options.is_a?(Hash) && to = options[:to]
raise ArgumentError, "Delegation need a target.Supply an options with a :to key as the last argument(e.g. delegate :hello, to: :greet"
end
to = to.to_s
file, line = caller(1,1).first.split(':')
line = line.to_i
methods.each do |method|
module_eval <<~EOF, file, line
def #{method}(*args, &block)
_ = #{to}
_.#{method}(*args, &block)
end
EOF
end
end
end
class Stack
attr_reader :que
def initialize()
@que = []
end
delegate :push, :pop, to: :que
end
Stack.new.push 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment