Created
October 27, 2015 03:33
-
-
Save dznz/53c5662b3fa64ebb1dce to your computer and use it in GitHub Desktop.
Simple decorator example
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
require 'delegate' | |
class SimpleDecorator < SimpleDelegator | |
attr_reader :context | |
def initialize(raw, view_context = nil) | |
@context = view_context if view_context | |
super raw | |
end | |
def self.wrap(collection, view_context = nil) | |
collection.map do |obj| | |
new obj, view_context | |
end | |
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
require 'lite_helper' | |
require 'delegate' | |
require_relative '../../app/decorators/simple_decorator' | |
describe SimpleDecorator do | |
class TestDecorator < SimpleDecorator | |
def test_context_method | |
context.helper_method | |
end | |
end | |
let(:context) do | |
double('view context').tap do |c| | |
allow(c).to receive(:helper_method) | |
end | |
end | |
describe 'decorating collections' do | |
it 'decorates collections via .wrap' do | |
arr = [1, 2] | |
wrapped_array = TestDecorator.wrap(arr) | |
wrapped_array.each do |item| | |
expect(item).to be_a(SimpleDecorator) | |
end | |
end | |
it 'injects an optional context' do | |
arr = [1, 2] | |
wrapped_array = TestDecorator.wrap(arr, context) | |
wrapped_array.each{|item| item.test_context_method } | |
expect(context).to have_received(:helper_method).twice | |
end | |
end | |
context 'when given a view context' do | |
it 'can be initialised with a view context' do | |
raw = double('raw object') | |
wrapped = TestDecorator.new(raw, context) | |
wrapped.test_context_method | |
expect(context).to have_received(:helper_method) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment