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

后端 未结 4 1868
太阳男子
太阳男子 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:14

    I'd say you should always pass the variables explicitly to your helper for 2 reasons:

    • you control exactly what you do

    • above all, you can test your helper

    0 讨论(0)
  • 2020-12-13 18:22

    Receive them as a param. Otherwise, as the app grows, it gets very difficult to trace where the instance vars are being set when refactoring, troubleshooting, etc.

    Also, I believe there's a general best practice to only use instance vars in views within the initial template...and from there you should pass the var into helpers and other partials.

    0 讨论(0)
  • 2020-12-13 18:23

    Since helper messages are mixed in to all controllers, hence available to all views (including partials and layouts), it's always wise to establish a clear contract - the parameters.

    The only exception I could think of is when a instance variable is also available to all views and controllers, like a menu or something similar.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题