Commit e5a29b45 authored by Rémy Coutable's avatar Rémy Coutable

Improve presenter factory

Signed-off-by: default avatarRémy Coutable <remy@rymai.me>
parent bf789ff5
module Gitlab
module View
module Presenter
class Factory
def initialize(subject, **attributes)
@subject = subject
@attributes = attributes
end
def fabricate!
presenter_class.new(@subject, @attributes)
end
private
def presenter_class
@subject.class.const_get('Presenter')
end
end
end
end
end
module Gitlab
module View
class PresenterFactory
def initialize(subject, user: nil)
@subject = subject
@user = user
end
def fabricate!
presenter =
if presenter_class.ancestors.include?(SimpleDelegator)
delegator_presenter
else
simple_presenter
end
presenter
.with_subject(subject)
.with_user(user)
end
private
attr_reader :subject, :user
def presenter_class
"#{subject.class.name.demodulize}Presenter".constantize
end
def delegator_presenter
presenter_class.new(subject)
end
def simple_presenter
presenter_class.new
end
end
end
end
require 'spec_helper'
describe Gitlab::View::Presenter::Factory do
let(:variable) { create(:ci_variable) }
describe '#initialize' do
context 'without optional parameters' do
subject do
described_class.new(variable)
end
it 'takes a subject and optional params' do
expect { subject }.not_to raise_error
end
end
context 'with optional parameters' do
subject do
described_class.new(variable, user: 'user')
end
it 'takes a subject and optional params' do
expect { subject }.not_to raise_error
end
end
end
describe '#fabricate!' do
subject do
described_class.new(variable, user: 'user', foo: 'bar').fabricate!
end
it 'exposes given params' do
expect(subject.user).to eq('user')
expect(subject.foo).to eq('bar')
end
it 'detects the presenter based on the given subject' do
expect(subject).to be_a(Ci::Variable::Presenter)
end
end
end
require 'spec_helper'
describe Gitlab::View::PresenterFactory do
let(:appearance) { build(:appearance) }
let(:broadcast_message) { build(:broadcast_message) }
before do
class AppearancePresenter
include Gitlab::View::Presenter
end
class BroadcastMessagePresenter < SimpleDelegator
include Gitlab::View::Presenter
end
end
describe '#initialize' do
subject do
described_class.new(appearance)
end
it 'takes a subject and optional params' do
expect { subject }.not_to raise_error
end
end
describe '#fabricate!' do
context 'without delegation' do
subject do
described_class.new(appearance).fabricate!
end
it 'does not forward missing methods to subject' do
expect { subject.title }.to raise_error(NoMethodError)
end
end
context 'with delegation' do
subject do
described_class.new(broadcast_message).fabricate!
end
it 'forwards missing methods to subject' do
expect(subject.message).to eq(broadcast_message.message)
end
end
end
end
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment