LoginSignup
3
2

More than 5 years have passed since last update.

[rails]ViewのDRY

Last updated at Posted at 2015-08-16

partialを用いたdry

dry前

html.erb
<!DOCTYPE html>
<html>
<head>
  <title>hoge</title>
</head>
<body>
  <div>
    <% if @japanese.age >= 20 %>
      <p>もっと飲め!</p>
    <% else %>
      <p>飲むな!</p>
    <% end -%>
  </div>
  <div>
    <% if @american.age >= 22 %>
      <p>もっと飲め!</p>
    <% else %>
      <p>飲むな!</p>
    <% end -%>
  </div>
</body>
</html>

dry後

html.erb
<!DOCTYPE html>
<html>
<head>
  <title>hoge</title>
</head>
<body>
  <div>
    <%= render partial: "app/views/hoge/alert", locals: {person: @japanese, adult_age: 20} %>
  </div>
  <div>
    <%= render partial: "app/views/hoge/alert", locals: {person: @american, adult_age: 22} %>
  </div>
</body>
</html>

partialファイル
app/views/hoge/_alert.html.erb

html.erb
<div>
  <% if person.age >= adult_age %>
    <p>もっと飲め!</p>
  <% else %>
    <p>飲むな!</p>
  <% end -%>
</div>

helperを用いたdry

dry前

html.erb
<!DOCTYPE html>
<html>
<head>
  <title>hoge</title>
</head>
<body>
  <% if @user.age >= 18 %>
    <a href="http://matome.naver.jp/odai/2135298257006394001">リンクヘ飛ぶ</p>
  <% else %>
    貴方は未成年なので、閲覧できません。
  <% end -%>
</body>
</html>

dry後

html.erb
<!DOCTYPE html>
<html>
<head>
  <title>hoge</title>
</head>
<body>
  <%= adult_check(@user.age)%>
</body>
</html>

app/helper/adult_check.rb

def adult_check(age)
  if age >= 20 
    return link_to "リンクへ飛ぶ", "http://matome.naver.jp/odai/2135298257006394001"
  else
    return "貴方は未成年なので、閲覧できません。"
end
3
2
0

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
3
2