Should Rails helpers assume an instance variable exists or should they receive them as parameters?

后端 未结 4 1869
太阳男子
太阳男子 2020-12-13 17:59

I\'m wondering if there\'s a specific programming principle (Demeter?) that supports the idea that Rails helpers should never use controller instance variables, rather, they

4条回答
  •  时光取名叫无心
    2020-12-13 18:29

    I don't know if there is any named principle governing this sort of thing but I would pass an argument. Not only will the argument make your helper easier to test and your application's data flow easier to follow but it will also let you use one helper for a single instance as well as a list; if you pass an argument then both:

    <%= cockadoodledoo @egg %>
    

    and:

    <% @eggs.each do |egg| %>
        <%= cockadoodledoo egg %>
    <% end %>
    

    will work as expected without introducing a special cockadoodledoo that handles a list in @eggs rather than a single @egg.

提交回复
热议问题