开发者

In Rails, is there a way to selectively load files in the view from application layout?

开发者 https://www.devze.com 2022-12-28 05:37 出处:网络
So in my Rails applicati开发者_如何转开发on, I\'m trying to set up Javascript testing on certain views.

So in my Rails applicati开发者_如何转开发on, I'm trying to set up Javascript testing on certain views.

Right now, I'm doing this by having a conditional in each view..

<% if AppConfig['js_testing'] %>
<script>
...
</script>
<% end %>

If I have it on each page, there's a lot of code duplication. Is there a way manage everything from the application layout?


There's a few places you can put this that will help reduce duplication. The main layout is an ideal candidate. Another possibility is a helper method that's a lot easier to introduce.

You could also define a conditional javascript_tag helper method that will only introduce the JavaScript if your trigger is set. Usually this is along the lines of:

def javascript_testing_tag(content)
  AppConfig['js_testing'] ? javascript_tag(content) : ''
end

Then it's a pretty straightforward exercise to wrap all your test scripts with that conditional. It will make it easier to refactor things later should the logical trigger for this behavior change.

The optimal implementation depends on what kind of scripting content you're introducing. If it's tied closely to the JavaScript that may be on a particular view, you may be stuck doing this.

An alternative is to simply tag each page and have a testing JavaScript harness that will trigger specific behavior depending on the structure of the document. For example, if there's an element div#user_list you might run testUserList().

It is then trivial to simply not include the testing JavaScript file in non-testing environments.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号