I have a fragment of JavaScript that I want to add to a page, but only in the production environment. Does rails have a way to insert or conditionally include on deployment. I know I could do "if Rails.env.production?" But I'd rather not do this condition check every time the page is loaded.
I wouldn't be worried about the overhead of one if statement.
Why not use a custom helper method:
def snippet
if RAILS_ENV == "production"
javascript_tag "whatever"
elsif . . .
end
then you can use the same syntax:
<%= snippet %>
and you get a couple benefits:
access to other rails helpers
your config file won't be littered with raw html
What I do in this situation is create a constant in each environment's config file:
#config/environments/development.rb
SNIPPET = ""
#config/environments/production.rb
SNIPPET = "<script src='whatever.js'></script>"
#app/views/file.html.erb
<%= SNIPPET %>
Related
Hey,
I want to be able to put all of my pages' scripts in my application layout, and load each one for the appropriate page.
I came across this [question][1], and I thought I can put the scripts inside of partials and do it the same way that is indicated in the mentioned question, however I'm trying to find the best way for scripts.
Would it be something like :
yield :scripts if condition
or
unless condition
content_for scripts do
end
end
or any other 'best' way ?
Note: Each page has its own script saved under the same name of the page.
Solved
I relied on the recommendations of #damien at the comments with the link he provided to come up with something like this:
In my helpers:
def javascript_exists?(script)
script = "#{Rails.root}/app/assets/javascripts/#{[params[:controller], params[:action]].join('_')}.js"
File.exists?(script) || File.exists?("#{script}.coffee")
end
In my application layout:
<%= javascript_include_tag [params[:controller], params[:action]].join('_'), :media => "all" if javascript_exists?([params[:controller], params[:action]].join('_')) %>
So to each controller, and to each action in the controller, the appropriate .js file gets included if it exists.
There is config.assets.compile=true parameter which enables so called "live compilation".
I need Rails to compile one specific asset (sample.css.scss.erb) on each request in live mode but the rest of assets should be still precompiled.
How can I achieve this?
Option 1 - put sample.css.scss.erb in a path different from config.assets.manifest (default="public/assets") and add it with javascript_include_tag
Option 2 - Remove it from the config.assets.precompile
config.assets.precompile -= %w( sample.css.scss.erb )
Make sure you clean then precompile to test it.
I did not test either option, please let us know if any works for you.
Live compilation for file is required when css is preprocessed by .css.erb file.
It means dynamically compiling css.
For example : allowing users to set the colors and would like to conditionally use "live compilation"
In that case i will suggest dynamically rendering /users/:id/styles.css.erb instead of live compilation.
Reason there might be millions of users and in production environment using Ec2 instance will cost you more. That's why i will suggest below solution:
First define your custom action on the UsersController:
# config/routes.rb
match '/users/:id/styles' => 'users#styles', :as => :user_styles
Link to the "stylesheet" in your layout:
# app/views/layouts/application.html.erb
= stylesheet_link_tag 'application', user_styles_path(current_user, :format => 'css')
Define the action in your controller. You could do whatever you want to retrieve the user's preferences here:
# app/controllers/users_controller.rb
class UsersController < ApplicationController
def styles
#colors = User.find(params[:id]).colors
end
end
That action will automatically render this view:
# app/views/users/styles.css.scss.erb
$background-color: <%= #colors[:background] %>;
body {
background-color: $background-color;
}
More ideas and suggetions are most welcome.
In my Rails 3.2 app (Ruby 1.9) I get following error when using path helpers in Coffeescript.
undefined local variable or method `new_user_session_path'
In my partial _usermenu.html.haml that works fine:
= link_to t('user.login'), new_user_session_path
In my app/assets/javascripts/metamenu.js.coffee.erb that throws above error:
$.get("<%= new_user_session_path %>")
Isn't it possible to use x_path and x_url helpers in coffeescript erb's?
This is because you are not within the view context inside of your assets. Adding an erb extension to the file doesn't change this, it simply allows you to evaluate embedded ruby.
If this is a one-off scenario, your best bet is to simply use the string itself.
$.get("/sign_in")
If you really wanted to you could create a partial that output a script tag that output your helper methods into js variables and access them that way.
# in your layout
<%= render 'url_helpers' %>
# in app/views/layouts/_url_helpers.html.erb
<script>
window.new_user_session_path = "<%= new_user_session_path %>";
# add more if necessary
</script>
# in your coffeescript
$.get(#new_user_session_path)
Also worth keeping in mind that this will obviously never work for member routes where your passing an instance of a model to the url helper as that is definitely not available to coffeescript. Remember, in production assets are precompiled so you can't use anything dynamic. For that you can only really rely on setting up actions in your controller to respond to JS calls.
Old post, but still accessible from Google.
In rails 4 (and certainly at least 3 too) you can use the route helpers to insert your js files easily:
assets/javascript/my_file.js.coffee.erb
<% self.class.include Rails.application.routes.url_helpers %>
window.index_route = '<%= index_path %>'
What would be the best way to pass values inside a .coffee script? Renaming the file to .erb breaks my app so what are the alternatives?
checkout this rails guide. this section : 2.3.3 JavaScript/CoffeeScript and ERB
You can use rails code in .coffee-script file. It's built-in feature.
2nd Edit___
If the file is in assets pipeline then you need to add .erb extension at end of coffee file so that the rails tag works otherwise there is no need to add .erb extension if you moves the file in views folder rails tag works there.
You can either (1) move the file into your app/views directory (so it won't be in the asset pipeline), or (2) pass the information via query string.
(1) app/views/users/script.js.coffee.erb
var username = <%= #user.name %>
(2) I'm using this function
<%= link_to "User", user_path(#user, :username => #user.name) %>
...
var username = getParameterByName('username')
Untested but this is the general idea.
If I generate a new controller in Rails 3.1, also a javascript file with the name of the controller will added automatically. Firstly, I thought this javascript file will used only, when the related controller is called.
By default there is the instruction //= require_tree . in the application.js-file, that include every javascript file on it's tree.
How could I load only the controller specific script?
To load only the necessary name_of_the_js_file.js file:
remove the //=require_tree from application.js
keep your js file (that you want to load when a specific page is loaded) in the asset pipeline
add a helper in application_helper.rb
def javascript(*files)
content_for(:head) { javascript_include_tag(*files) }
end
yield into your layout:
<%= yield(:head) %>
add this in your view file:
<% javascript 'name_of_the_js_file' %>
Then it should be ok
An elegant solution for this is to require controller_name in your javascript_include_tag
see http://apidock.com/rails/ActionController/Metal/controller_name/class
<%= javascript_include_tag "application", controller_name %>
controller_name.js will be loaded and is in the asset also, so you can require other files from here.
Example, rendering cars#index will give
<%= javascript_include_tag "application", "cars" %>
where cars.js can contain
//= require wheel
//= require tyre
Enjoy !
I always include this inside my layout files. It can scope your js to action
<%= javascript_include_tag params[:controller] if AppName::Application.assets.find_asset("#{params[:controller]}.js") %>
<%= javascript_include_tag "#{params[:controller]}_#{params[:action]}" if AppName::Application.assets.find_asset("#{params[:controller]}_#{params[:action]}.js") %>
Your problem can be solved in different ways.
Add the assets dynamically
Please consider that this isn't a good solution for the production mode, because your controller specifics won't be precompiled!
Add to our application helper the following method:
module ApplicationHelper
def include_related_asset(asset)
# v-----{Change this}
if !YourApp::Application.assets.find_asset(asset).nil?
case asset.split('.')[-1]
when 'js'
javascript_include_tag asset
when 'css'
stylesheet_link_tag asset
end
end
end
end
Call the helper method in your layout-file:
<%= include_related_asset(params[:controller].to_param + '_' + params[:action].to_param . 'js') %>
Create specific assets for your controller actions. E. g. controller_action.js
Please don't forget to change YourApp to the name of your app.
Use yield
Add <%= yield :head%> to your layout head
Include your assets from your action views:
<% content_for :head do %>
<%= javascript_include_tag 'controller_action' %>
<% end %>
Please see the Rails guides for further information.
I like albandiguer's solution. With which I've found that javascript/coffeescript assets are not individually precompiled. Which causes all sorts of errors trying to use javascript_path. I'll share my solution to that problem after I address an issue a few people mentioned in his comments. Mainly dealing with only a partial set of controller named JavaScript files.
So I built an application helper to detect if the file exists in the javascript directory regardless of .coffee/.js extension:
module ApplicationHelper
def javascript_asset_path(basename)
Sprockets::Rails::Helper.assets.paths.select{|i|
i =~ /javascript/ and i =~ /#{Rails.root}/
}.each do |directory|
if Dir.entries(directory).map {|i| i.split('.')[0]}.compact.
include? basename
return File.join(directory, basename)
end
end
nil
end
end
This method will return the full path to the javascript file if it exists. Otherwise it returns nil. So following Pencilcheck's comment you can add this method for a conditional include:
<%= javascript_include_tag(controller_name) if javascript_asset_path(controller_name) %>
And now you have a proper conditional include. Now for the issue of precompiled assets. Generally for optimization you don't want assets precompiled individually. You can however do it if you must:
# Live Compilation
config.assets.compile = true
You can add this do your environment config file. Test it in your development environment file first. Again this is ill-advisable. The Rails asset pipeline uses Sprockets to optimize everything:
Sprockets loads the files specified, processes them if necessary,
concatenates them into one single file and then compresses them (if
Rails.application.config.assets.compress is true). By serving one file
rather than many, the load time of pages can be greatly reduced
because the browser makes fewer requests. Compression also reduces
file size, enabling the browser to download them faster.
PLEASE READ the documentation for further details of the mechanics of Sprockets (Asset Pipeline) http://guides.rubyonrails.org/asset_pipeline.html
Assets aren't precompiled individually. For example when I try:
<%= javascript_include_tag 'event' %>
I get:
Sprockets::Rails::Helper::AssetFilteredError: Asset filtered out and
will not be served: add Rails.application.config.assets.precompile +=
%w( event.js ) to config/initializers/assets.rb and restart your
server
So you can include which assets to be precompiled individually. We just need to add the relevant controller named javascript files in our asset initializer. Well we can do this programatically.
To get a list of controller names I will use ecoologic's example:
all_controllers = Dir[
Rails.root.join('app/controllers/*_controller.rb')
].map { |path|
path.match(/(\w+)_controller.rb/); $1
}.compact
And now to get the name of all javascript files that match the basename of the controller name you can use the following:
javascripts_of_controllers = Sprockets::Rails::Helper.assets.paths.select{|a_path|
a_path =~ /javascript/ and a_path =~ /#{Rails.root}/
}.map {|a_path|
Dir.entries(a_path)
}.flatten.delete_if {|the_file|
!the_file['.js']
}.collect {|the_file|
the_file if all_controllers.any? {|a_controller| the_file[a_controller]}
}
Then you can try:
# config/initializers/assets.rb
Rails.application.config.assets.precompile += javascripts_of_controllers
This will get you a list of all javascript files, without directory path, that match your controller name. Note if your controller name is plural, the javascript name should be as well. Also note if the controller is singular and the javascript file is plural this will still include it because of the_file[a_controller] will succeed on a partial match.
Feel free to try this out in your Rails.application.config.assets.precompile setting. I know that this gets you the list of files correctly. But I'll leave you to test it. Let me know if there are any nuances involved with precompiling this way as I am curious.
For a very thorough explanation on how assets precompile see this blog: http://www.sitepoint.com/asset-precompile-works-part/
I recently found a simple approach to use generated scripts for specific controller. I use for that solution gem gon. Add in a controller:
class HomesController < ApplicationController
before_filter :remember_controller
private
def remember_controller
gon.controller = params[:controller]
end
end
After that open your homes.js.cofee and add in the beginning of file:
jQuery ->
if gon.controller == "sermons"
# Place all functions here...
That is all.