Uber simple presenters using Ruby's SimpleDelegator.
Add this line to your application's Gemfile:
gem 'resubject', '~> 0.0.1'
And then execute:
$ bundle
Resubject works on top of SimpleDelegator
which simply delegates every method call to the delegated object. Example:
class Box < Struct.new(:name, :items)
end
class BoxPresenter < Resubject::Presenter
def contents
items.join(', ')
end
end
Then use the delegator:
box = Box.new('Awkward Package', ['platypus', 'sloth', 'anteater'])
presentable = BoxPresenter.new(box, nil)
presentable.contents
# => platypus, sloth, anteater
If you have a collection of objects and want to add a presenter to each one, use Resubject.all
boxes = [box1, box2, box3]
BoxPresenter.all boxes
# => [<BoxPresenter>, <BoxPresenter>, <BoxPresenter>]
If you're using rails, Resubject automatically includes helpers in your controllers and views
class BoxesController < ActionController::Base
def index
@boxes = present Boxes.all
end
end
The #present
mehtod will automatically identify the presenter class by the object's class name. If you want to customize the class:
def index
@boxes = present Boxes.all, SpecialBoxPresenter
end
It also accepts multiple presenters:
def index
@boxes = present Boxes.all, BoxPresenter, ExtendedBoxPresenter
end
Or if you prefer, you can use the #present
method directly into your views
<%= present(@box).contents %>
- Felipe Elias Philipp - coderwall.com/felipeelias
- Piotr Jakubowski - coderwall.com/piotrj
- Fork it
- Create your feature branch (
git checkout -b my-new-feature
) - Commit your changes (
git commit -am 'Add some feature'
) - Push to the branch (
git push origin my-new-feature
) - Create new Pull Request