Rails and Page Specific Javascript - ruby-on-rails

Ok, I realise this question has been asked many times but the answers never seems to address the issue/question I have with this.
I have a js file that I would like to include on specific pages only. There are many responses that suggest that I put files into folders and then in the manifest file reference only those folders - for example this Railscast (at about 06:20) talks about this.
However, I only have one application layout file (and I guess this could be the area I'm lacking in) - therefore this file points to the application.js manifest and therefore I can't see how I can include things conditionally.
It's a bit like this resource too - http://railsapps.github.io/rails-javascript-include-external.html - scroll down to the page-specific scripts sub heading and it repeats what the Railscast suggests. But nothing is mentioned of multiple application layout files.
If anyone can help me clarify what to do in this situation I would be most grateful.
I should perhaps point out that I'm using Rails 4.

You can use content_for in your views to "inject" content into the layout when said view is to be rendered. See: using-the-content-for-method
You'd need to do a few things to make this happen:
Add the placeholder to yield the content in the layout. ex.
<%= yield :js %>
Add the block (to be yielded) to your view. ex:
<%= content_for :js do %>
<%= javascript_include_tag "my_script" %>
<% end %>
If you are using the asset pipeline in production and you want to reference a particular asset like a "my_script.js", in your production.rb or relevant environment config.you will need to precompile it using:
config.assets.precompile=["my_script.js"]

In application.html.erb, use this to add controller specific javascript instead of application specific javascript. Make sure you remove require_tree.
<%= javascript_include_tag params[:controller] %>
Read more on this topic on Rails Guide.

Related

Adding page-specific CSS to Rails Asset Pipeline

This is a question that several people have asked before, but none of the questions were quite asked or answered in a way that I found helpful, so I'm writing the question and answer that I would have found helpful.
I have a Rails 3.1+ app using the asset pipeline. There's one specific action that I want to have use different CSS. (In my specific case, I have a page that is intended to be printed, so it truly needs completely different CSS and does not need any Javascript.) Currently, I have only one application-specific CSS file. How do I add the new CSS file and direct the asset pipeline to use my file?
For example, right now, my app/assets looks like
app/assets
/javascript
application.js
custom.js.coffee
/css
application.css
custom.css.scss
I want to add a print.css file that is used by the view of a specific action. This view will not use the application.css file. How do I add print.css?
I found this blog post to be very helpful: http://blog.seancarpenter.net/2012/11/05/page-specific-javascript-with-the-asset-pipeline/. My answer paraphrases what this blogger already wrote and fills in a few missing details.
First, it's important that you've read and understood the Rails Guide to the Asset Pipeline. Unfortunately, this guide doesn't clearly explain how to add action-specific assets, but it does cover some concepts you need to know. Made sure you understand these ideas:
That the asset pipeline compiles Javascript, CSS, and other assets so that Rails servers can cache assets for better performance.
That manifest files use commands like require, require_tree, and require_self to indicate which files are compiled together.
That in order for the asset pipeline to work properly in production, you need to manually run rake assets:precompile to produce the compiled, minified assets in the public directory.
These ideas are the minimum "need-to-know" pieces of information about the asset pipeline. If you don't already understand these ideas, you don't have an "expert or enthusiast" level of knowledge about the pipeline, and unfortunately, SO isn't the right place to learn this stuff. Fortunately, the the Rails Guide to the Asset Pipeline is a short 15-minute read and can get you up to speed quickly if you need it.
Second, these are the changes you need to make in order to ensure that the asset pipeline correctly sees and handles your new print.css file.
Follow these steps:
Add your print.css file to app/assets/css.
You'll need to create a manifest file that will show Rails where to find print.css. You need to do this, even though you only have a single CSS file you're adding. This is an easy step:
Add a file called print.js to app/assets/javascript.
Add this line to print.js:
//= require print
This will be the only line in the entire print.js file. If I understand correctly, Rails expects manifest files to have the file extension .js, which is why we aren't using print.css as the manifest file.
We now need to instruct Rails to find and use the print.js manifest. Add the following line in your config/application.rb file:
config.assets.precompile += %w( print.js )
We're almost finished! However, the already-present application.js manifest includes the line //= require_tree . which means that it will include your print.css file. This will cause your print.css styling to affect your entire site, not just the single view. There are two ways of dealing with this:
If application.js and print.js do not share any assets, you can use the stub command in your application.js to exclude the assets used in print.js. What this does is instruct application.js to remove any of the assets that print.js references from its own list of referenced files. Our modified application.js looks like:
(snip...)
require_tree .
stub print
See this answer for more information.
If your print.js and application.js files share some assets, you'll need to move all of the assets used by application.js into subdirectories. I didn't do this myself, so I'm not the most help in this area. Look at this answer for instructions.
Now we have included print.css in the asset pipeline. We now need to direct Rails to use print.css in your specific view.
Let's say your action is in the reports controller, and that the action is named print_reports. This means we have a reports_controller.rb file and a print_reports.html.erb (or .haml) file. We need to make several changes to these files.
To start, add a new layout in app/views/layouts. Perhaps call it print.html.erb. We'll use this new layout for your print_reports.html.erb file. Set it up as you desire. For a page intended to be printed, this will likely be very simple, such as
<html>
<head>
<title="Print">
</head>
<body>
<%= yield %>
</body>
</html>
Using a separate layout the disadvantage that it's difficult to keep this layout and the layout used by the rest of the application in sync, but if you are using separate CSS files for the action, it's unlikely that you want the layout to be the same anyway.
Add a stylesheet_link_tag in the layout's header pointing to your print.css:
<html>
<head>
<title="Print"/>
<%= stylesheet_link_tag "print" %>
</head>
<body>
<%= yield %>
</body>
</html>
In the controller, we'll tell Rails to use our new layout for the action. Add the line layout 'print', only: [:print_reports] to your controller:
class reports_controller < ApplicationController
layout 'print', only: [:print_reports]
#snip
See this question for more information and a few different approaches.
At this point, when you run the app, your print_reports action should be using print.css correctly!
Remember to run rake assets:precompile before deploying on the server.
Official Solution
It is documented in the official Rails Guides here: http://guides.rubyonrails.org/asset_pipeline.html#controller-specific-assets
Actually you can leave out the require_tree directive (located in application.css and application.js) then use this in your template:
For controller specific JavaScript:
<%= javascript_include_tag params[:controller] %>
For controller specific CSS:
<%= stylesheet_link_tag params[:controller] %>
All of you are putting very complicated answers.
1 Go to app/assets/stylesheets
2.Make a file with the extension .css
3.Go to config/initializers/assets.rb
4.Put this line of of code Rails.application.config.assets.precompile += %w( file.css )
5.Replace file.css with the file you created
6.Go to your html.erb file
7.Type this in the <head>, <%= stylesheet_link_tag "file" %>
8.Replace file with the filename(no extension in the name)
Good Job you linked the file!
There's one specific action that I want to have use different CSS.
Here's an alternative way to accomplish what you're looking for:
Add the controller name and action name to the app body in your /views/layouts/application.html.rb:
<body class="<%= controller_name %>-<%= action_name %>">
<%= yield %>
</body>
Then in your .scss file:
.controller_name-action_name {
// your css goes here
}
So if your controller was static_pages and your action was home:
.static_pages-home {
// your css goes here
}
Tada! Your css only appears for that specific action.
In your layout
<head>
// ...
<%= yield :stylesheets %>
</head>
In your view
<%= provide :stylesheets do %>
// your page-specific css
<% end %>

Rails - Assets loaded on all pages

So I'm kinda lost here. All my CSS/SCSS files are loaded everywhere on my app. But I have two different design (front and back) that I want to separate. How can I achieve that ?
Plus it's kinda useless that all js/css are loaded, even where they are not used. How can I control that ?
What you're wanting to do is control your layouts.
As your question is currently it's too broad for someone to give you a decent specific answer, it's like saying 'tell me about astrophysics, I don't understand how to launch a rocket right now'.
I would suggest to start with the rails guides relating to layouts and then come back with a more specific question once you have a better understanding.
http://guides.rubyonrails.org/layouts_and_rendering.html
There is also a great 11 minute video on RailsCasts which will help you understand and control the assets pipeline: http://railscasts.com/episodes/279-understanding-the-asset-pipeline
Where you are heading is say your app was about managing projects.
Make a copy of the application.css file called say project-manifest.css and use the same structure as that application.css for loading just the stylesheets you want.
Make a copy of views/layouts/application.html.erb to say projects-layout.html.erb
In the new projecs-layout file, update the reference to the css to point to project-manifest.css
Point your controller code to use your new layout
say you have:
# app/controllers/ProjectsController.rb
def show
# code here
# rails does a default render layout: 'application', its overwritten by adding an explict render
render layout: 'project-layout'
end
In your application.js and application.css there is a directive by default: require_tree. It will load all your js and css files to be precompiled later. This is done to make the clients to download the assets packet only once (as it will be cached by the browser) and make the app faster.
If you want to load specific javascript or stylesheet files for each controller, remove the require_tree directive and include them in their respective controller:
<%= javascript_include_tag params[:controller] %> or <%= stylesheet_link_tag params[:controller] %>
Check this out: http://guides.rubyonrails.org/asset_pipeline.html#controller-specific-assets

where to put external assets in ruby on rails project?

If I have Javascrips/CSS files from an ASP .NET Project and I want to put them in my Rails project. Where's the best place to put them? Do I need to change every url into <%= asset_path "img" %>?
Put it in assets folder and add below line in views:
To add CSS files:
<%= stylesheet_link_tag "test.css" %>
To add JavaScript files:
<%= javascript_include_tag 'test.js'%>
Building on #Unknown's answer:
Yes, you do need to use asset_path, or one of the sprocket helpers, to refer to your assets in your CSS file so that they will properly include the MD5 fingerprint. Plus, this way you get the right asset between development and production (since they don't live in public while in development). Here's the relevant guide: http://guides.rubyonrails.org/asset_pipeline.html#coding-links-to-assets
According to http://railsapps.github.io/rails-javascript-include-external.html
The best practise for DRY and speed (according to article above) is to download all files to your projects assets folders, put them in the assets pipe for each application.js/.css and let rails compile them into one application.js and application.css in production mode. There are several ways to do this in detail (see link) The preferred way according to article for speed and DRY-practise is to call all js and css from application.css/.js and not put stylesheet_link_tag, calling css or js from view-files. This even though you may have one specific user.js which you only want to use on users page. Though there are ways to load specific files into specific views (see article for details)
Ecxept from having to call them in once in head of application.html(.haml/.erb):
= stylesheet_link_tag "application", :media => "all"
= javascript_include_tag "application"
If you are calling files in css eg. an image, as long as you have the image in "assets/images" you only need to refer to the images as 'image.jpg' in your css/js-files.

Defining separate views and assets for admin interface in a Rails app

I'm trying to build a CMS for my site in Rails and I want to have separate styles for all the views that people reading my site will be able to see, namely index and show views, and the views that handle creating, updating and deleting views. I understand that I should probably separate these two areas out into separate controllers and namespace all the admin ones' routes, but I'm at a loss on how to do the views.
Is there any way to specify a layout, including stylesheets and javascript files, for a specific set of controllers? Note I'm using Rails 3.1 so as things are right now all my stylesheets and scripts get compiled into single files that are served with every view.
I was running around looking for a very similar thing. And was lucky enough to find a great tutorial article by Iain Hecker.
Backends in Rails 3.1
Its set up using Namespacing and Template Inheritance. And the best part is he uses the inherited_resources gem by Jose Valim which really cleans up your controllers.
Anyway, it really got me on the right track.
Also, what will help is in your default application.js make sure to use:
//= require_directory .
instead of
//= require_tree
This will make sprockets only load files in the current directory. Then you can add an admin/ folder with its own application.js file doing the same thing.
Then of course in you layouts/application.html.erb you use:
<%= javascript_include_tag "application" %>
And in layouts/admin/application.html.erb:
<%= javascript_include_tag "admin/application" %>
Hope that helps...
Adam.
For CSS, I like to add some body classes in my application.html.erb that allow me to separate a) admin from non-admin, and b) the various controllers/actions from each other. Here's what my body tag often looks like
<body class="<%= 'admin' if admin? %> <%= params[:controller].parameterize %> <%= params[:controller].parameterize %>_<%= params[:action].parameterize %>">
where admin? is an ApplicationHelper method defined as follows:
def admin?
controller.class.name.split("::").first=="Admin"
end
For JS, you need to tackle view specific javascript. For that I'm going to point you here. The multiple manifest file technique discussed there could be useful for you, as you could construct an admin.js file that contains everything you need within your Admin namespace.
UPDATE: I thought this was a good question, so I wrote up a more thorough response here
One way of getting what I think you want would be to use a <div id="index"> index stuff ....
and then use nested layouts to style the div

Where do you put small snippets of CSS codes for rails app?

I know that most CSS codes go under app/assets/stylesheets, but I have some snippets of CSS codes that are specific to only certain pages. For now, I just have these small CSS codes included in the view files, but I feel like there's ought to be a better way of handling this.
Any suggestion?
Rails convention is to put these in controller specific CSS files:
For example, if a ProjectsController is generated, there will be a new
file at app/assets/javascripts/projects.js.coffee and another at
app/assets/stylesheets/projects.css.scss. You should put any
JavaScript or CSS unique to a controller inside their respective asset
files, as these files can then be loaded just for these controllers
with lines such as <%= javascript_include_tag params[:controller] %>
or <%= stylesheet_link_tag params[:controller] %>.
Putting the CSS inside the views isn't a good idea as you lose features (fingerprinting, auto minification) that the asset management in Rails provides.
Read more here: http://guides.rubyonrails.org/asset_pipeline.html#how-to-use-the-asset-pipeline

Resources