Skip to content

Instantly share code, notes, and snippets.

@dreamr
Last active December 23, 2015 17:59
Show Gist options
  • Save dreamr/6672685 to your computer and use it in GitHub Desktop.
Save dreamr/6672685 to your computer and use it in GitHub Desktop.
learning aid for the jr devs, passing ruby lambdas as first class args
printer = ->(msg) { puts "#{msg}" }
logger = ->(msg) { File.open("test.txt", "a") {|f| f.write(msg) } }
class Person
def initialize(first_name, last_name)
@first_name, @last_name = first_name,
last_name
end
def display_name(printer)
name = "#{@first_name} #{@last_name}"
printer.call(name)
name
end
end
require 'minitest/autorun'
require 'mocha/setup'
require 'stringio'
module Kernel
def capture_stdout
out = StringIO.new
$stdout = out
yield
return out
ensure
$stdout = STDOUT
end
end
describe Person do
subject { Person.new("James", "OKelly") }
describe "#display_name" do
subject { Person.new("James", "OKelly").
display_name(printer) }
describe "when the printer is a putser" do
let(:hof) { printer }
it "must use the putser to print the name" do
stdout = capture_stdout do
subject
end
stdout.string.must_equal "James OKelly\n"
end
end
describe "when the printer is a logger" do
let(:hof) { logger }
it "must use the logger to print the name" do
subject
File.read("test.txt").must_equal "James OKelly"
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment