public
Clone URL: git://github.com/nmerouze/action_presenter.git
Search Repo:
action_presenter / README.rdoc
100644 67 lines (41 sloc) 1.487 kb

Action Presenter

Inspired by : http://www.caboo.se/articles/2007/8/23/simple-presenters

Requirements

  • Rails 2.1 and later.

Install

        ruby script/plugin install git://github.com/nmerouze/action_presenter.git

Usage

Here’s a presenter :

        class ArticlePresenter < ActionPresenter::Base
                def title
                        h @source.title
                end
        end

And to call it in the views, there are present() and p() :

        <%= present(@article).title %> or <%= p(@article).title %>

Instead of a tradionnal loop or iterator, you can use present() :

        <% present(@articles) do |article| %>
                <h2>&lt;%= article.title %></h2>
        &lt;% end %>

If you want to use methods from the source record inside the iterator (or somewhere else), you just have to use source() or s() :

        &lt;% present(@articles) do |article| %>
                <h2>&lt;%= h source(article).title %></h2>
        &lt;% end %>

Render files

You can also render files for a presenter method :

        class ArticlePresenter &lt; ActionPresenter::Base
                def title
                        render :title
                end

                def body
                        render :body, :msg => 'Hello World!'
                end
        end

The partial for title will be located in app/presenters/article/title.html.erb :

        &lt;%=h article.title %>

The partial for body will be located in app/presenters/article/body.html.erb :

        &lt;%= article.body + msg %>

Presenters in your plugins

You can have presenters in plugins. Just create a directory app/presenters and you’re ready to go. It’s great if you have Engines too.

Contact

nicolas.merouze (at) gmail (dot) com