From ca616d8962f302ed91f5d9e7b5d7251d2094466d Mon Sep 17 00:00:00 2001 From: Daniel Schierbeck Date: Fri, 28 Aug 2015 10:52:46 +0200 Subject: [PATCH] Add a DelegatePresenter base class Subclasses of this class can easily delegate presenter methods to a backing object. A parameter with the same name as the class (e.g. `product` for `ProductPresenter`) must be passed and its value will receive delegated calls. --- lib/curly.rb | 1 + lib/curly/delegate_presenter.rb | 23 +++++++++++++++++++++++ spec/delegate_presenter_spec.rb | 14 ++++++++++++++ 3 files changed, 38 insertions(+) create mode 100644 lib/curly/delegate_presenter.rb create mode 100644 spec/delegate_presenter_spec.rb diff --git a/lib/curly.rb b/lib/curly.rb index 7f48e98..2f1f497 100644 --- a/lib/curly.rb +++ b/lib/curly.rb @@ -50,5 +50,6 @@ def self.valid?(template, presenter_class) require 'curly/compiler' require 'curly/presenter' +require 'curly/delegate_presenter' require 'curly/template_handler' require 'curly/railtie' if defined?(Rails) diff --git a/lib/curly/delegate_presenter.rb b/lib/curly/delegate_presenter.rb new file mode 100644 index 0000000..d516be9 --- /dev/null +++ b/lib/curly/delegate_presenter.rb @@ -0,0 +1,23 @@ +require 'curly/presenter' + +module Curly + class DelegatePresenter < Curly::Presenter + def self.delegates(*methods) + methods.each do |method| + class_eval <<-RUBY + def #{method} + @#{delegatee_name}.#{method} + end + RUBY + end + end + + def self.inherited(subclass) + self.presented_names += [subclass.delegatee_name] + end + + def self.delegatee_name + name.split("::").last.underscore.sub(/_presenter$/, "") + end + end +end diff --git a/spec/delegate_presenter_spec.rb b/spec/delegate_presenter_spec.rb new file mode 100644 index 0000000..e7f6fed --- /dev/null +++ b/spec/delegate_presenter_spec.rb @@ -0,0 +1,14 @@ +describe Curly::DelegatePresenter do + class PersonPresenter < Curly::DelegatePresenter + delegates :name, :age + end + + it "allows exposing methods on the passed object" do + context = double(:context) + person = double(:person, name: "Jane", age: 25) + presenter = PersonPresenter.new(context, person: person) + + expect(presenter.name).to eq "Jane" + expect(presenter.age).to eq 25 + end +end