LoginSignup
9
7

More than 5 years have passed since last update.

Rails のヘルパーについての悩み

Posted at

悩み

view にこんなコードがあったとする。

<a id="foo" href="<%= new_foo_path %>">
  <% if @foo.doable? %>
    <img src="/images/bar.gif" alt="実行可能" />
  <% else %>
    <img src="/images/baz.gif" alt="実行不可能" />
  <% end %>
</a>

@foo#doable? によって、リンク先は同じだけれども、画像を変えたい。(例は微妙だけど、そういう事があるはず)

まず Rails のヘルパーを使うように修正。

<%
  image_tag_for_link = if @foo.doable?
    image_tag("bar.gif", alt="実行可能")
  else
    image_tag("baz.gif", alt="実行不可能")
  end
%>
<%= link_to image_tag_for_link, new_foo_path, :id => "foo" %>

テンプレートに条件分岐が入るのが嫌なので、ヘルパーにする

def image_tag_for_new_foo_link(foo)
  if foo.doable?
    image_tag("bar.gif", alt="実行可能")
  else
    image_tag("baz.gif", alt="実行不可能")
  end
end
<%= link_to image_tag_for_new_foo_link(@foo), new_foo_path, :id => "foo" %>

こうなると image_tag_for_foo_link がオブジェクト指向っぽく無い事に気付いてモヤモヤしだす。(Ruby はオブジェクト指向言語である!)
つまり、こう書きたい。

<%= link_to @foo.image_tag_for_new_link, new_foo_path, :id => "foo" %>

かといって、これを Foo モデルには書きたくない。モデルはデータを提供するけど、表示の仕方だとかどんなタグを使うかだとかに関心を持ちたくない

解決策

ActiveDecorator を使えば良いんだろうなーと思っている。
https://github.com/amatsuda/active_decorator

更なる悩み

今やってる案件が Rails 2 系なの…(´・ω・`)

その他の悩み

こういう時に link_to までヘルパーにするか、image_tag だけをヘルパーにするか。

9
7
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
7