-
-
Save israelb/9acfd87b40b11d117e81 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 Car < ActiveRecord::Base | |
attr_accessible :make, :car_model, :colour | |
def lots_of_model_code | |
# etc, etc | |
end | |
end |
This file contains hidden or 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
require 'delegate' | |
class CarPresenter < SimpleDelegator | |
def description | |
# we can take advantage of memoization to speed it up if repeated calls to methods :) | |
@description ||= "This is a #{model.make} #{model.car_model} of #{colour_or_empty} colour" | |
end | |
def colour_or_empty | |
@colour ||= model.colour.blank? ? "unknown" : model.colour | |
end | |
# Returns ref to the object we're decorating | |
# a method to help readability. | |
# If using this n>1 times then consider moving upto superclass | |
def model | |
__getobj__ | |
end | |
end |
This file contains hidden or 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
require 'test_helper' | |
class CarPresenterTest < ActiveSupport::TestCase | |
def setup | |
@car = cars(:car_one) # a car with Ford, Focus and Red attributes | |
@car_presenter = CarPresenter.new(@car) | |
end | |
# a non-exhaustive few tests for class | |
test "should give description with correct attributes" do | |
assert_equal "This is a Ford Focus of Red colour", @car_presenter.description | |
end | |
test "should give description when colour is empty" do | |
@car.colour = nil # empty the colour attribute | |
car_presenter = CarPresenter.new(@car) | |
assert_equal "This is a Ford Focus of unknown colour", car_presenter.description | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment