How do I use different js to load in production and development environments?

Asked 2 months ago, Updated 2 months ago, 3 views

I am using rails 3.2.

in development mode
app/assets/javascripts/ajaxzip3.js

in production mode
app/assets/javascripts/ajaxzip3-https.js

Is it possible to use ?

I use ajaxzip3 zip code search library.
This is because I use https in the production environment and http in the development environment.

The link above contains the following:It's easy to operate only in the production environment, but it won't be fun if it doesn't work in the development environment (^^;

).
# For http servers, use http://ajaxzip3.googlecode.com/svn/trunk/ajaxzip3/ajaxzip3.js.
# For https servers, use https://ajaxzip3.googlecode.com/svn/trunk/ajaxzip3/ajaxzip3-https.js. 

javascript ruby-on-rails

2022-09-30 14:19

2 Answers

The request.protocol and the Helper method will help you write clearly.

#app/helper/application_helper.rb
module ApplicationHelper
  defaultajaxzip3_include_tag
    file_name = ssl ?? 'ajaxzip3-https.js': 'ajaxzip3.js'
    javascript_include_tag(file_name)
  end

  def ssl?
    request.protocol=='https://'
  end
end

<%#app/views/layouts/application.html.erb%>
<!DOCTYPE html>
<html>
<head>
  <title>Your app name</title>
  <%=stylesheet_link_tag 'application', media: 'all'%>
  <%=javascript_include_tag'application'%>
  <%=ajaxzip3_include_tag%>
  <%=csrf_meta_tags%>
</head>
<body>

<%=yield%>

</body>
</html>

Also, if you want to use it for production, you may need to specify the file in config.assets.precompile.

#config/environments/production.rb
config.assets.precompile+=%w(ajaxzip3-https.js)

I hope it will be helpful.


2022-09-30 14:19

app/views How about writing the following in HTML?

<%if Rails.env.production?%>
  <script src="https://ajaxzip3.googlecode.com/svn/trunk/ajaxzip3/ajaxzip3-https.js"></script>
<%else%>
  <script src="http://ajaxzip3.googlecode.com/svn/trunk/ajaxzip3/ajaxzip3.js"></script>
<%end%>

This is what Slim looks like.

-if Rails.env.production?
  script src="https://ajaxzip3.googlecode.com/svn/trunk/ajaxzip3/ajaxzip3-https.js"
- else
  script src="http://ajaxzip3.googlecode.com/svn/trunk/ajaxzip3/ajaxzip3.js"


2022-09-30 14:19

If you have any answers or tips


© 2022 OneMinuteCode. All rights reserved.