Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Curly – Rethinking the view layer

Curly – Rethinking the view layer

Presented at RailsConf 2015.

Daniel Schierbeck

April 22, 2015
Tweet

More Decks by Daniel Schierbeck

Other Decks in Programming

Transcript

  1. ERb? <ul id="products"> <% for product in products %> <li>

    <h2><%= product.title %></h2> Only <%= product.price %> <p><%= product.description %></p> </li> <% end %> </ul>
  2. Liquid <ul id="products"> {% for product in products %} <li>

    <h2>{{ product.title }}</h2> Only {{ product.price | format_as_money }} <p>{{ product.description | truncate: 200 }}</p> </li> {% endfor %} </ul>
  3. So, what do we want? • Safe, declarative templates •

    Logic in a separate place • Testable! • Full integration with our existing Rails views
  4. Curly! • HTML in templates, logic in presenters • Presenters

    have full access to all the Rails goodies! • Can be used alongside ERb
  5. class ... < Curly::Presenter def link ... end def popularity

    ... end def meta ... end def description ... end end <li class="search-result"> {{link}} {{popularity}} <div class="..."> {{meta}} </div> <div class="..."> {{description}} </div> </li>
  6. <% if @post.comments_enabled? && can?(:comment, @post) %> <%= render 'comment_form',

    post: @post %> <% else %> <p><%= t(".comments_disabled") %></p> <% end %> <% comments = @post.comments.page(@page || 1).per(30) %> <h2><%= comments.count == 0 ? t(".no_comments") : t(".comment_count", count: comments.count) %></h2> <ul class="comments"> <%= render comments %> </ul> <%= paginate(comment) %>
  7. <% if @post.comments_enabled? && can?(:comment, @post) %> <%= render 'comment_form',

    post: @post %> <% else %> <p><%= t(".comments_disabled") %></p> <% end %> <% comments = @post.comments.page(@page || 1).per(30) %> <h2><%= comments.count == 0 ? t(".no_comments") : t(".comment_count", count: comments.count) %></h2> <ul class="comments"> <%= render comments %> </ul> <%= paginate(comment) %>
  8. class Posts::ShowPresenter < Curly::Presenter presents :post, :page def comment_form if

    @post.comments_enabled? && can?(:comment, @post) render 'comment_form', post: @post else content_tag :p, t(".comments_disabled") end end def comment_count if comments.count == 0 t(".no_comments") else t(".comment_count", count: comments.count) end end ... end
  9. Traditional view testing • Render view with a bunch of

    variables set • Parse the result • Make assertions
  10. describe UserPresenter do describe "#name" do it "adds a (moderator)

    note for moderators" do presenter = UserPresenter.new(context, user: user) presenter.name.should == "John (moderator)" end end end Unit testing presenters
  11. Use the best tool for the job Markup languages for

    structure Programming languages for logic
  12. • Daniel Schierbeck • @dasch on GitHub and Twitter •

    Come talk with me! Thank you! http://github.com/zendesk/curly