📕
SEIRFX
  • Introduction
  • About These Notes
  • Schedule
  • Unit 2
    • Node
      • Internet Fundamentals
      • Full-Stack Fundamentals
      • Intro to Node
      • Node Modules
      • Node Packages
    • Express
      • Intro to Express
      • Routes
      • Routes Lab
      • Views
      • Templates
      • Layouts & Controllers
    • CRUD & REST
      • GET & POST
      • GET & POST Lab
      • PUT & DELETE
    • API Calls in Express
      • Axios
      • Request (no longer maintained)
    • Sequelize
      • Terminology
      • Setup
      • Using Models
      • Seeding Data
      • Validations and Migrations
      • Resources
      • 1:M Relationships
      • N:M Relationships
    • Express Authentication
      • Research Components
      • Code Components
      • Auth in Theory
        • Sessions
        • Passwords
        • Middleware
        • Hooks
      • Auth in Practice
        • Create the User
        • User Signup
        • Sessions
        • User Login
        • Authorization and Flash messages
  • Development Workflow
    • Command Line
      • The Terminal
      • Filesystem Navigation
      • File Manipulation
      • Additional Topics
    • Intro to Git
      • Version Control
      • Local Git
      • Remote Git
      • Git Recipes
    • Group Collaboration
      • Git Workflows
      • Project Roles and Tools
    • VS Code Tips & Tricks
  • HTML/CSS
    • HTML
    • CSS Selectors
    • CSS Box Model and Positioning
      • Box Model
      • Display and Positioning
      • Flexbox
      • Grid
      • Flexbox & Grid Games
      • Floats and Clears
      • Additional Topics
    • Advanced CSS
      • Responsive Design
      • Pseudo-Classes/Elements
      • Vendor Prefixes
      • Custom Properties
      • Additional Topics
    • Bootstrap
    • CSS Frameworks
    • Accessibility
  • JavaScript
    • Primitives
    • Arrays
    • Objects
      • Objects Lesson
      • Objects quick guide
      • Object-ception
    • Control Flow
      • Boolean Expressions
      • Conditionals
      • Loops
      • Promises
    • Functions
      • Scope
      • Callbacks
      • Higher Order Functions
      • Callbacks Review Lab
      • Timing Functions
      • Iterators
      • Combining Data Types
      • Combining Data Types Lab
    • Javascript in the browser
      • DOM and Events
      • DOM Manipulation
      • DOM Review
      • DOM Review Lab
      • HP DOM Lab
      • Programmatic DOM Manipulation
      • Grids & Pyramids
      • DOM & Data
      • DOM Events
      • Color Palette Picker
      • Sketchpad
    • HTML5 Canvas
    • How To Reduce Redundancy
    • OOP
      • Westworld Lab
      • OOP Factories
      • OOP Inheritance
      • OOP Inheritance Lab
      • Tomagotchi Lab
      • OOP Space Battle
      • OOP Snowman
      • (2019) JavaScript OOP
      • (2016) OOP with Classes
      • (1995) OOP with Prototypes
      • Constructors
      • Prototypes
    • Intro to TDD
    • Scoping
    • Inheritance
      • Prototypal Inheritance
      • Call, Apply, and other Functions
      • ES6 Inheritance
      • Resources
    • Custom Node Modules
    • Additional Topics
      • AJAX, Fetch, and Async/Await
      • AJAX w/JSON and Localstorage
        • AJAX w/JSON
        • Local Storage
      • Async module
      • Data Scraping
  • jQuery
    • Intro
      • DOM Manipulation
      • Reddit Practice
      • Styling
      • Events
    • Plugins
    • AJAX
  • APIs
    • Fetch
    • AJAX w/jQuery
    • AJAX w/Fetch
  • Databases
    • Intro to SQL
    • Advanced SQL
    • MongoDB
      • Intro to NoSQL
      • CRUD in MongoDB
      • Data Modeling
      • Intermediate Mongo
  • Left over Node/Express
    • Testing with Mocha and Chai
    • Mongoose
      • Mongoose Associations
    • JSON Web Tokens
      • Codealong
    • Additional Topics
      • oAuth
      • Geocoding with Mapbox
      • Geocoding and Google Maps
      • Cloudinary
      • Websockets with Socket.io
      • SASS
  • Ruby
    • Intro to Ruby
    • Ruby Exercises
    • Ruby Classes
    • Ruby Testing with Rspec
    • Ruby Inheritance
    • Ruby Data Scraping
  • Ruby on Rails
    • Intro to Rails
    • APIs with Rails
    • Asset Pipeline
    • Rails Auth and 1-M
      • Auth Components
    • Rails N:M
    • ActiveRecord Polymorphism
    • Additional Topics
      • oAuth
      • SASS
      • Rails Mailers
      • Cloudinary
      • Jekyll
  • React (Updated 2019)
    • ES6+/ESNext
      • Const and Let
      • Arrow Functions
      • Object Literals and String Interpolation
      • ES6 Recap
      • ES6 Activity
    • Intro to React
      • Create React App
      • Components and JSX
      • Virtual DOM
      • Props
      • Dino Blog Activity
      • Nested Components
      • Lab: LotR
    • React State
      • Code-Along: Edit Dino Blog
      • Lab: Simple Calc
      • Lifting State
    • React Router
      • Browser History/SPAs
      • React Router (lesson and full codealong)
      • Router Lab
    • Fetch and APIs
      • APIs with Fetch and Axios
      • Fetch the Weather
    • React Hooks
    • React LifeCycle
      • Lab: Component LifeCycle
    • React Deployment
    • Additional Topics
      • React Frameworks
        • Material UI Theming
      • Typescript
        • More Types and Syntax
        • Tsconfig and Declaration Files
        • Generics with Linked List
      • Redux
      • TypeScript
      • Context API
      • React Native
  • Meteor
  • Deployment and Config
    • Installfest
      • Mac OSX
      • Linux
      • Git Configuration
      • Sublime Packages
    • Deploy - Github Pages
    • Deploy - Node/Sequelize
    • Deploy - Node/MongoDB
    • Deploy React
    • Deploy - Rails
      • Foreman (Environment Variables)
    • Deploy - AWS Elastic Beanstalk
    • Deploy - S3 Static Sites
    • Deploy - Django
    • Deploy - Flask
  • Data Structures and Algorithms
    • Recursion
    • Problem Solving - Array Flatten
    • Binary Search
    • Algorithm Complexity
    • Stacks and Queues
    • Bracket Matching
    • Ruby Linked Lists
      • Sample Code
      • Beginner Exercises
      • Advanced Exercises
    • JS Linked Lists
      • Sample Code
      • Beginner Exercises
      • Beginner Solutions
    • Hash Tables
    • Intro to Sorting
    • Insertion Sort
    • Bucket Sort
    • Bubble Sort
    • Merge Sort
    • Quick Sort
    • Heap Sort
    • Sorting Wrapup
    • Hashmaps
    • Trees and Other Topics
  • Python
    • Python Installation
    • Intro to Python
    • Python Lists
    • Python Loops
    • Python Dictionaries
    • Python Sets and Tuples
    • Python Cheatsheet
    • Python Functions
    • Python Classes
    • Python Class Inheritance
    • Intro to Flask
    • Intro to SQLAlchemy
      • Flask and SQLAlchemy
    • Using PyMongo
    • Intro to Django
    • CatCollector CodeAlong
      • URLs, Views, Templates
      • Models, Migrations
      • Model Form CRUD
      • One-to-Many Relations
      • Many-to-Many Relations
      • Django Auth
    • Django Cheatsheet
    • Django Auth
    • Django Polls App Tutorial
    • Django School Tool Tutorial
    • Django 1:M Relationships
    • Custom Admin Views
    • Data Structures and Algorithms
      • Recursion
      • Binary Search
      • Stacks and Queues
      • Linked Lists
      • Binary Trees
      • Bubble Sort
      • TensorFlow & Neural Networks
    • Adjacent Topics
      • Raspberry Pi
      • Scripting
  • Assorted Topics
    • History of Computer Science
    • Regular Expressions
    • Being Successful in SEI
    • Internet Fundamentals
      • Internet Lab
    • Adjacent Workflow
      • UX/UI
      • Wireframing Exercise: Build an Idea
      • Agile
    • Post SEI
      • Learning Resources
      • Deliverables -> Portfolio
      • FAQ
  • Projects
    • Project 1
    • Project 2
    • Project 3
      • Project 3 Pitch Guidelines
    • Project 4
    • Past Projects
      • Project 1
      • Project 2
      • Project 3
      • Project 4
      • Portfolios
    • Post Project 2
    • MEAN Hackathon
      • Part 1: APIs
      • Part 2: Angular
    • Portfolio
  • Web Development Trends
  • Resources
    • APIs and Data
    • Tech Websites
    • PostgreSQL Cheat Sheet
    • Sequelize Cheat Sheet
    • Database Administration
  • Archived Section
    • (Archived) ReactJS
      • Intro to React
        • Todo List Codealong
        • Additional Topics
      • Deploy React
      • React with Gulp and Browserify
        • Setting up Gulp
        • Additional Gulp Tasks
      • React Router
        • OMDB Router
        • OMDB Search
        • Additional Resources
      • React Animations
        • CSS Animations
    • AngularJS
      • Intro to AngularJS
        • Components and SPA
        • Create an Angular App
      • Angular Directives and Filters
      • Angular Animation
      • Angular Bootstrap Directives
        • Bootstrap Modals
      • Angular $http
      • Angular Services
        • Service Recipes
        • ngResource
        • Star Wars Codealong
      • Angular Routing
      • Angular + Express
      • Angular Authentication
        • Additional Topics
      • Angular Components
      • Angular Custom Filters
      • Angular Custom Directives
Powered by GitBook
On this page
  • Objectives
  • JavaScript
  • application.js
  • Stylesheets
  • Images
  • Images in views (erb)
  • Images in CSS (using SCSS)
  • Passing data to the front-end (gon)
  • gon setup
  • Using gon
  • Pitfalls
  • AJAX in Rails
  • Additional Reading

Was this helpful?

  1. Ruby on Rails

Asset Pipeline

Objectives

  • Incorporate JavaScript, CSS, SCSS, images, and other static files into a Rails application

  • Describe the Asset Pipeline in laymans' terms

  • Utilize helper methods/tags for including static resources

  • Use gon to pass data to the front-end

We can work with JavaScript, CSS, and images in Rails just like we did in our front-end only projects. Rails uses the concept of an Asset Pipeline to handle pre-processing and loading of static assets. The "Rails way" is to put all of your assets (JavaScript, CSS/SASS, images) in the assets folder. Just do it!

JavaScript

To load JavaScript files in Rails we simply create .js files in the app/assets/javascripts directory and Rails will automatically load them in the head of the page using <script> tags.

To adjust the load order, we can add the scripts along with the //= lines at the bottom of application.js

application.js

application.js is used to load other JavaScript files and allows us to change the load order of the files. You CAN put JavaScript code directly in this file. But it's best practice to avoid this and use separate files as before.

At the bottom of application.js there are a few lines that look like comments and start with //= these are used to specify which files to load and in what order. The last line (//= require_tree .) loads all of the files in the javascripts directory that aren't loaded explicitly above.

For example, if we had a file called importantScript.js in our javascripts directory and we needed it to be loaded first we could simply do something like this...

//= require 'importantScript.js'
//= require jquery_ujs
//= require turbolinks
//= require_tree .

Stylesheets

Rails uses SASS, which is a preprocessor for CSS that allows us to use some additional features that standard CSS doesn't support. These files end with the .scss file extension and are processed on the server (back-end) before they are sent to the user/browser as plain CSS.

Just like with JavaScript, Rails will auto-load any CSS or SCSS file that are in app/assets/stylesheets.

Also, similar to JavaScript we can adjust the load order by editing the bottom of application.css, and again we should avoid putting CSS directly in this file.

Images

We can load images by placing them in app/assets/images and using the rails image_tag helper to load them for us.

Images in views (erb)

If we have a file app/assets/images/pic.jpg we can display it in an erb file like this:

<%= image_tag 'pic.jpg' %>

We can also get a string of the image URL/path by calling image_url or image_path.

Images in CSS (using SCSS)

We also have access to a image_url helper method in scss files. It will be used in place of the standard css url('/path/to/image.jpg') format.

.some-class {
  background-image: image_url('pic.jpg');
}

NOTE: make sure the file is named scss and not just css. The css files are served to the browser as-is (no pre-processing), but scss are run through the sass pre-proccessor first which will run the image_url method and insert the correct image path.

Passing data to the front-end (gon)

We can pass data from a controller to front-end JavaScript using a gem called "gon" which allows us to easily pass any data from the back-end to the front-end.

gon setup

To use gon (just like any other gem) we need to add it to our GemFile. After adding it remember to run bundle install and then restart your server with rails s

in GemFile

gem 'gon'

Then we need to add a tag inside of our <head> tag that will load the backend values as javascript so we can use them in our frontend.

in layouts/application.html.erb

<%= include_gon %>

Be sure to add this line BEFORE javascript_include_tag that way the variables it defines will be available in your .js files.

Using gon

gon is very simple to use. It exposes a variable called gon the controller. gon is a hash that we can add any values to and they will be available on the front-end automatically.

In controller

def index
  gon.something = "hello"
  gon.people = ['Lenny', 'Brian', 'Daniel']
  gon.tasks = Task.all
end

In JS

console.log(gon.something);
//outputs: "hello"

console.log(gon.people);
//output: ['Lenny', 'Brian', 'Daniel']

console.log(gon.tasks);
//outputs: an array of objects for all tasks in the database

Pitfalls

There is only one major "gotcha" with gon and that is that gon won't be defined in JavaScript unless you assign something to it in the controller.

Assume we didn't assign any values to gon in the controller...

in JS

console.log(gon.taco);

This would throw an error because gon is undefined. To avoid this problem we just need to check it using typeof.

if (typeof gon !== 'undefined') {
  console.log('taco is', gon.taco);
} else {
  console.log('there is no gon (or taco)');
}

AJAX in Rails

As an alternative to using gon, AJAX calls in Rails can be done if you have a controller action that returns JSON data. Here's an example. Let's assume this controller action can be accessed via the route GET /names.

class NamesController < ApplicationController
  def names
    names = Name.all
    render json: names
  end
end

When accessing GET /names, the response will contain JSON data.

In order to access this route via AJAX, we can create a JavaScript file that accesses this route. We'll need to account for Turbolinks on the page by encapsulating the AJAX call inside an event called ready page:load.

$(document).on('ready page:load', function() {
  $.get('/names').done(function(data) {
    console.log(data);
  });
});

This AJAX call can be triggered on form submission or button click by encapsulating the call within an event listener function. Example:

$(document).on('ready page:load', function() {
  $('#button').click(function() {
    $.get('/names').done(function(data) {
      console.log(data);
    });
  });
});

Additional Reading

PreviousAPIs with RailsNextRails Auth and 1-M

Last updated 4 years ago

Was this helpful?

Learn SASS here:

SASS
Rails Guides - Assets Pipeline
Rails API - Asset Tag Helpers
SASS documentation
gon gem