Yet Another

OO
Rails helper

Mark from Taiwan
twitter: @lulalala_it
github: @lulalala

 

Rails Helpers are not OO enough

We are OO 聖騎士

looks not OO! No stars!

looks OO! Zen!

<%= nicely_format_money(money) %>
<%= money.nice_format %>

Need different name for different class, no stars!

Can use same name! Zen!

<%= book_cover_image(@book) %>
<%= cd_cover_image(@cd) %>
<%= @book.cover_image %>
<%= @cd.cover_image %>

(I am a very

浅い
OO 聖騎士)

So people make gems to make helpers

OO

Draper gem

@article = Article.
           find(params[:id]).
           decorate
<%= @article.publication_status %>

You need to decorate in controller

Draper gem

class ArticleDecorator < Draper::Decorator
  delegate_all
  def publication_status
    h.link_to(
      status + " " + level, 
      article_path(42)
    )
  end
end
@user = User.first
<%= @user.link %>

Automagically decorate

everything for you.

module UserDecorator
  def link
    link_to full_name, website
  end
end

No need to type `h.link_to`.

`link_to` goes to decorator
`full_name` goes to model

So magical!

Decorator

ActiveRecord object

I (am hard to please and) feel magic may be dangerous

(steal)

🍴fork

lulalala/lulalala_presenter

 

@user = User.first
<%= @user.presenter.link %>

You access methods in presenter object,
in view.

Calling record.presenter
gives us a PORO 

class UserPresenter < LulalalaPresenter::Base
  def link
    h.link_to model.full_name, model.website
  end
end

`h` stands for helper,
which is view context object.

`model` is the model

Less Magic

ActiveRecord

object

Presenter

😞 ➡️ 😃

People complain:

"decorators" mix model with view together.

Now view methods

are in own object

You won't forget to remember to decorate it in controller

Only one look,

and you know it is presetnter

book.presenter.isbn_image_tag

😞 ➡️ 😃

When Rails.version += 0.1

gem break probability = foo

When Rails.version += 0.1

gem break probability = foo/bar

Please
Trytry

Epilogue

I found another gem which has even less magic

RobinBrouwer/exhibit

  • No magic of storing view context per thread
  • exhibit(@user)
    instead of
    @user.presenter

 

Perfect for magic-haters!

Good if you hate magic more than I do

lulalala_presenter

 

Mark from Taiwan
twitter: @lulalala_it
github: @lulalala

 

Made with Slides.com