Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
ruby delegator
#!/usr/bin/env ruby
# require 'pry'
# require 'byebug'
module DelegateMe
def delegate_methods(methods, to:)
[methods].flatten.each do |method_name|
define_method method_name do |*arg, &block|
base = send(to)
base.send(method_name, *arg) do
block.call
end
end
end
end
end
class Bear
def name
"Pooh"
end
def says(*args)
'"' + args.to_a.join(" ") + "\", said #{name}"
end
def backwards(&block)
((yield if block_given?) || "").reverse
end
end
class BearPresenter
extend DelegateMe
def initialize(bear)
@bear = bear
end
# attr_reader
def bear
@bear
end
delegate_methods([:name, :says, :backwards], to: :bear)
end
puts "Delegating..."
bear = Bear.new
bear_presenter = BearPresenter.new(bear)
puts bear_presenter.name
puts bear_presenter.says("whatever", "man")
reversed = bear_presenter.backwards do
bear_presenter.says("super")
end
puts reversed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment