Skip to content

Commit

Permalink
Add a DelegatePresenter base class
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
dasch committed Aug 28, 2015
1 parent 93a1b7d commit ca616d8
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 0 deletions.
1 change: 1 addition & 0 deletions lib/curly.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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)
23 changes: 23 additions & 0 deletions lib/curly/delegate_presenter.rb
Original file line number Diff line number Diff line change
@@ -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
14 changes: 14 additions & 0 deletions spec/delegate_presenter_spec.rb
Original file line number Diff line number Diff line change
@@ -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

0 comments on commit ca616d8

Please sign in to comment.