Last active
January 5, 2017 17:33
-
-
Save yukas/7d68738c33a5aece045885fbe6394466 to your computer and use it in GitHub Desktop.
Plain Old Decorators
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
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 |
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
# 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 |
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
# 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