0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

連番のインスタンス変数をinstance_variable_getメソッドでDRYにしようとしたけど用途が違った

Last updated at Posted at 2019-05-02

追記:DRY後(最終形)

@znz さんにコメントでご指摘をいただきました。ありがとうございます。
結局 instance_variable_get メソッドを使うより普通に配列でやるべきでした。
以下のように書けました。

schedule_controller.rb
# day_1,day_2 に値をセットする過程は省略
@days = [day_1,day_2]
schedule.html.erb
<% @days.each do |day| %>

...中略(Rubyとは直接関係のないHTML、CSSの記述など)...

  <%= render 'day', day: day %>
<% end %>

DRY後(一回目)

  • コントローラー側で @day_1@day_2 の2つのインスタンス変数をセットしているとします。
  • 下のコードでは _day.html.erb パーシャルを呼び出していますが、こう書くことで動的に生成したインスタンス変数名を指定できます。
schedule.html.erb
<% 2.times do |n| %>

...中略(Rubyとは直接関係のないHTML、CSSの記述など)...

  <% day_i = "@day_#{n + 1}" %>
    <%= render 'day', day: instance_variable_get(day_i) %>
<% end %>

DRY前

  • 下記のように render メソッドを並べても動きますが、中略にした部分も並べないといけませんので、やはりDRYにした方が良い感じですね。
schedule.html.erb
...中略(Rubyとは直接関係のないHTML、CSSの記述など)...

<%= render 'day', day: @day_1 %>

...中略(Rubyとは直接関係のないHTML、CSSの記述など)...

<%= render 'day', day: @day_2 %>

参考

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?