Skip to content

Instantly share code, notes, and snippets.

@rob-murray
Last active January 3, 2016 22:29
Show Gist options
  • Save rob-murray/8529104 to your computer and use it in GitHub Desktop.
Save rob-murray/8529104 to your computer and use it in GitHub Desktop.
Decorators, Presenters, Delegators and Rails - See http://robertomurray.co.uk/blog/2014/decorators-presenters-delegators-rails/
class Car < ActiveRecord::Base
# example Car fields
attr_accessible :make, :car_model, :colour
def lots_of_other_model_code
# etc, etc
end
end
require 'delegate'
class CarPresenter < SimpleDelegator
def description
@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
def model
__getobj__
end
end
require 'test_helper'
class CarPresenterTest < ActiveSupport::TestCase
def setup
@car = cars(:car_one) # a car with Ford, Focus and Red attributes
@decorated_car = CarPresenter.new(@car)
end
# a non-exhaustive set of tests for class
test "should give description with correct attributes" do
assert_equal "This is a Ford Focus of Red colour", @decorated_car.description
end
test "should give description when colour is empty" do
@car.colour = nil # empty the colour attribute
decorated_car = CarPresenter.new(@car)
assert_equal "This is a Ford Focus of unknown colour", decorated_car.description
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment