Created
February 27, 2020 16:25
-
-
Save bunnymatic/126ba4098003c97c44a7e20d54a51e0c to your computer and use it in GitHub Desktop.
ruby delegator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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