Skip to content

Instantly share code, notes, and snippets.

@bunnymatic
Created February 27, 2020 16:25
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 bunnymatic/126ba4098003c97c44a7e20d54a51e0c to your computer and use it in GitHub Desktop.
Save bunnymatic/126ba4098003c97c44a7e20d54a51e0c to your computer and use it in GitHub Desktop.
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