Skip to content

Instantly share code, notes, and snippets.

@yukas
Last active Jan 5, 2017
Embed
What would you like to do?
Plain Old Decorators
class Greeter
def greet(user)
user_name_decorator = UserNameDecorator.new(user)
@greeting = user_name_decorator.dear_mr_user
@greeting << "\n"
@greeting << "Bla bla bla"
...
@greeting << "\n"
end
end
# There can be number of user decorators for different purposes
#
class UserNameDecorator
attr_reader :user
def initialize(user)
@user = user
raise "No user given" unless user # Blowup earlier in case there is no user given
end
def dear_mr_user
"Dear mr. #{full_name}"
end
def full_name
"#{user.first_name} #{user.last_name}"
end
end
# Testing like a regular object
#
describe UserNameDecorator do
subject { described_class.new(user) }
describe "#dear_mr_user" do
let(:user) { create(:user, first_name: "Alex", last_name: "Pushkin") }
it "greets user" do
expect(subject.dear_mr_user).to eq("Dear mr. Alex Pushkin")
end
end
...
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment