Skip to content

Instantly share code, notes, and snippets.

@israelb
Forked from rob-murray/pres_model.rb
Created August 13, 2014 21:07
Show Gist options
  • Save israelb/9acfd87b40b11d117e81 to your computer and use it in GitHub Desktop.
Save israelb/9acfd87b40b11d117e81 to your computer and use it in GitHub Desktop.
class Car < ActiveRecord::Base
attr_accessible :make, :car_model, :colour
def lots_of_model_code
# etc, etc
end
end
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
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