Rails 4 assets pipeline : CSS, Javascript, Images

Assets pipeline

* concatenates to 1 CSS and to 1 JS
* precompiles minified/gzip CSS and JS
* write SCSS, Coffeescript
* asset fingerprinting ( MD5 hash ) after the file that will change after the new file is changed

Assets pipeline : /app/asset
served exactly as-is : /public

app/assets/stylesheets/application.css ( manifest file that contains directive )

*= require_self
*= require public # load public.css first
*= require_tree . # all files inside the tree

compiled

app/assts/stylesheets/application.css
|
v
public/app/assets/application-XXXXXXXXXXXXXXXXX.css
public/app/assets/application-XXXXXXXXXXXXXXXXX.css.gz

development env
* process SASS/CoffeeScript
* skips concatenation/compression/fingerprint

production
* pre-compile in advance

RAILS_ENV=production bundle exec rake assets:precompile

WARNING : you should test locally with production mode, or using QA server

1)CSS
app/assets/stylesheets
* public.css
* admin.css
public/stylesheets

Stylesheet helper

<%= stylesheet_link_tag('application', :media=>'all') %>

handle development/production env

SASS : “Syntactically Awesome Stylesheets”
requires sass-rails gem

bundle install

2)Javascript
app/assets/javascipts/application.js

//= require jquery
//= require jquery_ujs
//= require_tree .

public/javascripts

using jquery

requires jquery-rails gem

include javascript

<%= javascript_include_tag('application') %>

include snippet

<%= javascript_tag("alert('test');");

NOTE: this will generate

<script>//<![CDATA[ 
//]]>
</script>

include multiple

<%= javascript_tag do %>
alert('test');
<% end %>

rails change the layout

class ApplicationController:
layout 'application' # call "layouts/application.erb"

Escaping javascript using j( ) : when user submit portion, to prevent XSS

<% text = "test" %>
<% javascript_tag("alert('You said : #{j(text)}');") %>

NOTE: j() will add \’, \”

h() # escape HTML

CoffeeScript.org
requires coffee-rails and uglifier gem

3)images
app/assets/images
public/images # user upload content
# on the production, it would exists here
# on development, rails route to assets folder

Image Upload Gem
Paperclip, CarrierWave

Image Helper

<%= image_tag('logo.png') %>
<%= image_tag('logo.png', :size => '90x55', :alt => 'logo') %>
<%= image_tag('logo.png', :width => 90, :height => 55) %>

Using Image in CSS

url('/assets/test.png')
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s