Skip to content
This repository

Render the same "view hash" in HAML, ERB, or Javascript Templates

branch: master

Fetching latest commit…

Octocat-spinner-32-eaf2f5

Cannot retrieve the latest commit at this time

Octocat-spinner-32 docs @ 6a39389
Octocat-spinner-32 lib
Octocat-spinner-32 test
Octocat-spinner-32 .gitignore
Octocat-spinner-32 .gitmodules
Octocat-spinner-32 MIT-LICENSE
Octocat-spinner-32 README.md
Octocat-spinner-32 Rakefile
Octocat-spinner-32 action-presenter.gemspec
README.md

ActionPresenter

What is this?

  • A class to clean up your controllers.
  • An interface between the view and the controller
  • A pattern that allows you to serve the same response to JSON or HAML. This is the main reason for this library.

JavaScript Templates and HAML

I got excited when I started playing around with JavaScript templates, but quickly realized I'd have to rewrite a lot of the HAML I'd already written (and there is no exact JavaScript HAML engine). So that got me thinking...

All the view needs is a hash. You don't need those helper modules Rails ships with. Think about it this way: if you can't use those methods in JavaScript, then you shouldn't be using them in your HAML templates. Abstracted out all the way, your JavaScript templates and HAML templates should look almost exactly alike; they only differ in the syntax.

What this means is you construct a hash and can render it as a

  • HAML template which is sent as static HTML to the browser
  • Inline JSON string which is run through a JavaScript template
  • JSON string via AJAX, which is run through a JavaScript template

This solves 3 problems:

  1. Caching. You don't want to have to cache the JSON and HTML responses separately, that just doubles your cache size. Now, you can cache the hash itself (in Memcached), and/or the JSON string. Cache levels: record from db -> hash -> json.
  2. Multiple ways of writing the code. You can write the AJAX response code the same way you write the HAML rendering code.
  3. Cleans up your helpers.

Install

gem install action-presenter

Usage

Inside the directory app/presenters, create files like user_presenter.rb:

class UserPresenter < ActionPresenter::Base
  def url
    link_to title, user_path(user)
  end

  def title
    t(:"users.title", :name => user.name, :role => user.role)
  end

  def render
    {
      :url  => url,
      :name => user.name
    }
  end
end

You can access the same variables/scope as if you were in the HAML template (all of the controller and view variables). This means you can access the tag methods such as link_to, interpolator helper methods, url helpers, date helpers, number helpers, etc.


MIT License. © 2011 Big Lobby LLC. All rights reserved.

Something went wrong with that request. Please try again.