最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Configure Rails to use different js in development and production - Stack Overflow

programmeradmin1浏览0评论

I want Rails to inject different js files in development and production modes.

Example:

Development:

<script src="/javascripts/jquery.js" type="text/javascript"></script>
<script src="/javascripts/myscripts.js" type="text/javascript"></script>

Production:

<script src=".4.2/jquery.min.js" type="text/javascript"></script>
<script src="/javascripts/myscripts.min.js" type="text/javascript"></script>

Is it possible to achieve it in Rails 3?

Regards, Alexey Zakharov

I want Rails to inject different js files in development and production modes.

Example:

Development:

<script src="/javascripts/jquery.js" type="text/javascript"></script>
<script src="/javascripts/myscripts.js" type="text/javascript"></script>

Production:

<script src="http://ajax.googleapis./ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script>
<script src="/javascripts/myscripts.min.js" type="text/javascript"></script>

Is it possible to achieve it in Rails 3?

Regards, Alexey Zakharov

Share Improve this question edited Sep 14, 2010 at 18:17 Jeff 21.9k6 gold badges53 silver badges55 bronze badges asked Sep 14, 2010 at 18:01 Alexey ZakharovAlexey Zakharov 25.1k42 gold badges127 silver badges198 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 7

From at least Rails 3, you can pass the javascript_include_tag helper the symbol :defaults which is defined inside your config/application.rb at the variable config.action_view.javascript_expansions[:defaults] =

This will currently be mented out and will always at least include application.js.

If you want to define a different set of defaults for production and development then leave this line mented out and open up config/environments/production.rb and config/environments/development.rb. Any settings defined in here will override any set in application.rb and only apply in the relevant environment. For your example, you would want the following:

# development.rb
config.action_view.javascript_expansions[:defaults] = %w(jquery.js myscripts.js)

# production.rb
config.action_view.javascript_expansions[:defaults] = %w(http://ajax.googleapis./ajax/libs/jquery/1.4.2/jquery.min.js myscripts.min.js)

You could have a helper method load your js and perform the condition check as to which environment it is.

app/views/layouts/application.html.* (wherever you normally include your javascript)

load_javascript

app/helpers/application_helper.rb

def load_javascript
  if Rails.env.production?
    javascript_include_tag 'js1', 'js2', :cache => true
  else
    javascript_include_tag 'js3', 'js4'
  end
end

You could DRY it up a little further by having load_javascript only give you back a list of the files and have only one javascript_include_tag.

发布评论

评论列表(0)

  1. 暂无评论