• This repository has been archived on 23/Jul/2022
  • Stars
    star
    646
  • Rank 69,672 (Top 2 %)
  • Language
    Ruby
  • License
    MIT License
  • Created almost 10 years ago
  • Updated about 7 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Ditch the Rails Asset Pipeline and roll your own with Gulp

DEPRECATED: Use Blendid!

The work done in this repo has been rolled into a single dependency solution: Blendid!. You can set up your Rails project with the yarn run blendid -- init-rails command.

The Gulp Asset Pipeline on Rails

  • Leaves Sprockets and manifest files intact for use with gem installed assets
  • Transform and bundle CommonJS modules (js or coffee) with Browserify
  • Compile .sass/.scss with Libsass (node-sass through gulp-sass)
  • Autoprefix css
  • Optimize images (could be expanded to further process or resize images)
  • Compile an icon font + sass from a folder of SVGs
  • Full BrowserSync integration (the original Rails Asset Pipeline didn't work with live stylesheet injection)
  • Revision filenames in production for caching
  • Build assets on deploy with Heroku

Production Environment Demo (notice the revisioned asset filenames for caching)

This repo is only meant to be an example. You should fork and customize it with your own Rails setup and relevant Gulp tasks, or copy the relevant files into an existing project. To understand more about individual modules, read the documentation on their respective websites and repositories. Based on gulp-starter.

Running the Demo

Clone the repository

git clone https://github.com/vigetlabs/gulp-rails-pipeline.git

Enter into the directory and run bundle install

cd gulp-rails-pipeline
bundle install

Install javascript dependencies. Once npm install runs, the postinstall setting in package.json will run gulp build and do an initial build of your assets.

npm install

Start the rails server.

rails s

Run gulp and rejoice! This will start watching and recompiling files on the fly, as well as open a browser with BrowserSync running.

gulp

Try editing global.sass and watch how fast it reloads the css! Once you taste the speed of Libsass + BrowserSync, you'll never go back. Test out changing view code and javascript as well.

Asset File Structure

Asset File Structure

gulp/assets

This is where all your source files will live. Your source icons for icon fonts, sass files, js modules, and images. Anything that needs to get processed by Gulp. All assets are set up to compile to public/assets.

public/assets

The destination of your compiled and processed assets. The application.css and application.js manifest files in app/assets pull compiled code from this folder.

app/assets

The old default asset directory should only include manifest files, which are necessary if you need to require gem installed assets (e.g., jquery_ujs, turbolinks) with Sprockets. The manifest files pull in gem assets, as well as our compiled js and css files from /public/assets.

Rails setup notes:

config/application.rb

# Make public assets requireable in manifest files
config.assets.paths << Rails.root.join("public", "assets", "stylesheets")
config.assets.paths << Rails.root.join("public", "assets", "javascripts")

If you plan on continuing to use Sprockets to //require= gem assets, you'll include your compiled js and css files in the application.js and application.css manifests files. The snippet above tells Sprockets to look in our public/assets directories when searching for required files. With this implementation, you'll continue using the Rails javascript_include_tag and stylesheet_link_tag asset pipeline helpers to pull in your manifest files (and everything they require). If you end up not needing the pipeline at all, you can pull in your compiled css and js directly with the gulp_asset_path helper (see below) and regular html.

config/environments/development.rb

config.assets.debug = true
config.assets.digest = false

To fully take advantage of BrowserSync's live stylesheet injection, be sure to configure the two values above. Setting config.assets.debug to true tells Rails to output each individual file required in your application.js and application.css manifests, rather than concatenating them. This is the default setting in development. Setting config.assets.digest to false disables appending md5 hashes for caching with future Expires headers. With your individual files referenced and their file names unchanged, BrowserSync can reference and replace them properly as they get changed.

package.json

"scripts": {
  "postinstall": "gulp build"
},
"dependencies": {...}

After running npm install, Node will search the scripts object in package.json for postinstall, and will run the script if specified. gulp build compiles your assets. The build can be set up differently for different Rails environments. See below. A note about dependencies. Services like Heroku will ignore anything in devDependences, since it's technically a production environment. So be sure to put anything your build process needs to run in dependencies, NOT devDependencies.

gulp/tasks/build.js

// line 6
if(process.env.RAILS_ENV === 'production') tasks.push('rev');

If the RAILS_ENV is set to production, assets will be renamed with an appended md5 hash for caching with far future Expires headers, and any references in stylesheets or javascript files will be updated accordingly. For inline asset references in Rails Views, you can use the following asset helper.

app/helpers/application_helper.rb

def gulp_asset_path(path)
  path = REV_MANIFEST[path] if defined?(REV_MANIFEST)
  "/assets/#{path}"
end

Because we're storing our assets outside of the Rails Asset Pipeline, we need to re-implement the asset_path path helper as gulp_asset_path to reference un-hashed files in development, and the cacheable hashed versions of the files in production. This goes for other Rails Asset Pipeline helpers, such as <%= image_tag, 'asset.png' %>. Instead, use <img src="<%= gulp_asset_path('asset.png') %>">.

config/initializers/rev_manifest.rb

rev_manifest_path = 'public/assets/rev-manifest.json'

if File.exist?(rev_manifest_path)
  REV_MANIFEST = JSON.parse(File.read(rev_manifest_path))
end

You'll notice this constant referenced in the gulp_asset_path helper above. The gulp/tasks/rev.js that gets run in production outputs a rev-manifest.json file, mapping the original filenames to the revisioned ones. If that file exists when the app starts, the hashed filenames are used. If it doesn't exist, the filename references remain unchanged.

Deploying

To avoid git messiness and redundant rebases and merge conflicts, it's usually a good idea to .gitignore your compiled assets. This means you'll have to have them compile as part of your deploy process. In short, you'll need to ensure the following:

  1. Node is installed
  2. npm install runs
  3. gulp build runs on postinstall (specified in package.json)

These steps must complete before starting the Rails server.

Heroku

Heroku makes deploying SUPER easy, but there are a couple of things you'll need to do to get this running.

Since we're using Ruby (to run Rails) AND Node (to compile our assets with Gulp) in our setup, we need both running on our server. Heroku will automatically detect ONE of these at a time based on the presense of a Gemfile or package.json, but to get both running simultaneously, we need to specify multiple buildpacks in the order we want.

heroku buildpacks                     # view current buildpacks
heroku buildpacks:clear               # clear current buildpacks, if necessary
heroku buildpacks:add heroku/nodejs   # add the buildpacks we want ...
heroku buildpacks:add heroku/ruby     # ... in the order we want them

Now, when we deploy to Heroku, first npm install will run, then our postinstall script specified in package.json, and then bundle install will run.

Take note of the following:

  #production.rb line 25
  config.serve_static_files = ENV['RAILS_SERVE_STATIC_FILES'].present?

Heroku requires config.serve_static_files to be enabled, so be sure to either add RAILS_SERVE_STATIC_FILES as a config var in your Heroku settings, or manually set this to true in your production.rb file.

Capistrano

All we need to do is add a task to run npm install before we compile the assets.

The example below shows an example of using nvm (node version manager) to use the specified node version for your application.

# ./config/deploy.rb

before "deploy:assets:precompile", "deploy:npm_install"

namespace :deploy do
  desc "Run npm install"
  task :npm_install do
    invoke_command "bash -c '. /home/deploy/.nvm/nvm.sh && cd #{release_path} && npm install'"
  end
end

Original Blog Post: viget.com/extend/gulp-rails-asset-pipeline


Code At Viget

Visit code.viget.com to see more projects from Viget.

More Repositories

1

blendid

A delicious blend of gulp tasks combined into a configurable asset pipeline and static site builder
JavaScript
4,986
star
2

Twitter-Bootstrap-for-Omnigraffle

Omnigraffle stencil, template, and color picker modeled after Twitter Bootstrap
585
star
3

microcosm

Flux with actions at center stage. Write optimistic updates, cancel requests, and track changes with ease.
JavaScript
487
star
4

react-ink

A React component for adding material design style ink
JavaScript
325
star
5

colonel-kurtz

A Block Editor
JavaScript
318
star
6

sass-json-vars

Import variables as JSON into Sass
Ruby
294
star
7

grunt-complexity

A JavaScript complexity analysis grunt task.
JavaScript
221
star
8

sprig

Relational seeding for Rails apps
Ruby
208
star
9

jmapping

jQuery plugin for creating Google Maps from semantic markup
JavaScript
207
star
10

olive_branch

Handle camel/snake/dash case conversion
Ruby
180
star
11

acts_as_markup

Represent ActiveRecord Markdown, Textile, or RDoc columns as Markdown, Textile, or RDoc objects using various external libraries to convert to HTML.
Ruby
123
star
12

active_admin_associations

This extends ActiveAdmin to allow for better editing of associations.
Ruby
120
star
13

whitespace-tmbundle

TextMate bundle to remove trailing whitespace & tabs
115
star
14

capistrano_rsync_with_remote_cache

A deployment strategy for Capistrano 2.0 which combines rsync with a remote cache, allowing fast deployments from SCM servers behind firewalls.
Ruby
102
star
15

serialize_with_options

Simple XML and JSON APIs for your Rails app
Ruby
92
star
16

cachebar

A simple API caching layer built on top of HTTParty and Redis
Ruby
88
star
17

redirector

A Rails engine that adds a piece of middleware to the top of your middleware stack that looks for redirect rules stored in your database and redirects you accordingly.
Ruby
83
star
18

react-focus-trap

Traps focus for accessible dropdowns and modal content
JavaScript
81
star
19

stat_board

Simple dashboard of records created this week, this month, and all time, mountable as a Rails Engine.
Ruby
79
star
20

ensure-animation

Ensure animation runs until class loaded
JavaScript
76
star
21

nav_lynx

Rails helper to generate navigation links with a selected class.
Ruby
75
star
22

simplest_auth

Simple implementation of authentication for Rails
Ruby
73
star
23

tailwindcss-plugins

A collection of plugins for Tailwind CSS
JavaScript
58
star
24

interactive-wcag

A filterable and shareable version of the WCAG 2.0 spec.
46
star
25

storyboard

For making ADVENTURES
TypeScript
43
star
26

jquery.transport

Transport elements to other containers based upon media queries.
JavaScript
42
star
27

ruby-string-showdown

Double vs Single Quoted Ruby Strings... Which will emerge victorious??
Ruby
39
star
28

trackomatic

A high-performance tracking enhancement for Google Analytics.
JavaScript
34
star
29

an-isomorphic-chart

Charts are for everyone. A pending blog post.
JavaScript
33
star
30

otp

One-time pad programming exercise
Ruby
31
star
31

ruby_spark

Ruby Gem to make API calls to the Spark Cloud
Ruby
31
star
32

ars-arsenal

A react gallery picker
TypeScript
30
star
33

json-weight

Measure the weight of a JSON endpoint
JavaScript
30
star
34

augmented-card

Example project for ARKit Image Tracking blog post
Swift
29
star
35

simplest_status

Simple status functionality for Rails models.
Ruby
28
star
36

craft-color-swatches

PHP
27
star
37

ca11y

A lightweight accessible dependency-free datepicker
JavaScript
26
star
38

watch-dog

Monit + Sinatra + Monk + SQLite + Mustache = multi-site dowtime alert app
Ruby
25
star
39

jambells

HQ/Boulder Pointless Weekend Project
Elixir
25
star
40

craft-localeredirector

Craft plugin for detecting user language preferences and redirecting to the appropriate locale.
PHP
24
star
41

craft-videoembed

Craft plugin to generate an embed URL from a YouTube or Vimeo URL.
PHP
24
star
42

ffeud

Elixir
23
star
43

platomformio

Integration Atom IDE with PlatformIO
CoffeeScript
23
star
44

jest-with-nightmare

JavaScript
22
star
45

craft-profile

A command-line utility for capturing Craft CMS Profiling output and reporting averages.
JavaScript
22
star
46

sprig-reap

Sprig-Reap is a gem that allows you to output your application's data state to seed files.
Ruby
18
star
47

Screenless

A $55 alternative user interface for rapidly prototyping ideas
C++
16
star
48

foliage

A light, cursor-like tree data structure
JavaScript
15
star
49

canvas-instagram-filters

Demo for an upcoming blog post
JavaScript
15
star
50

simple-benchmark

A simple gem to benchmark spots in your Ruby / Rails code
Ruby
14
star
51

Material-Design-for-Omnigraffle

Omnigraffle stencil modeled after the Material Design sticker sheets
14
star
52

gangway

A client-side API abstraction layer
JavaScript
13
star
53

pointless-feedback

Rails Engine to handle basic user feedback
Ruby
13
star
54

craft-classnames

Craft plugin for conditionally joining css class names together in Twig templates. Really helps with wrangling Tailwind CSS.
PHP
11
star
55

is-it-viget

A demo app for viget.com tutorial
Swift
11
star
56

beginning-react-native

The online home of the SXSW 2016 Beginning iOS Development With React Native Workshop
11
star
57

special-delivery

A webhook event manager for Mailgun
Ruby
10
star
58

d3-builder

Builds D3 as a browserify dependency
JavaScript
10
star
59

checkoning

Visualizating team PR interactions
JavaScript
10
star
60

react-dragon

A very simple drag and drop component. Did I mention it was simple?
JavaScript
10
star
61

diode

An extremely small, single event emitter
JavaScript
9
star
62

prestotype

(WIP) Simple UX prototype boilerplate
JavaScript
9
star
63

craft-site-starter

PHP
8
star
64

craft-viget-base

PHP
7
star
65

slack_alert

A simple button that lights up, plays jingles, and interacts with Slack.
Ruby
7
star
66

rails_polymorphic_select

This is a simple Rails extension that allows you to create polymorphic select inputs for relationships that are polymorphic. It takes advantage of Rails 4.2 Global ID
Ruby
7
star
67

chronolog

Change Tracking for ActiveAdmin
Ruby
7
star
68

sxsw

SXSW Connected Devices Workshop Materials
Arduino
6
star
69

grunt-git-hooks-demo

A sample application to get started using Git hooks with Grunt.
JavaScript
6
star
70

trailbuddy-view-transition

Astro
6
star
71

reword

A tiny translator.
JavaScript
6
star
72

active_versioning

Plug-and-Play Versioning for Rails
Ruby
6
star
73

craft-sidebartoggle

Add the ability to hide the meta sidebar on element entry screens
PHP
5
star
74

gradebook

Example application for the Rails Developer position
5
star
75

VL-Date-Selects

EE plugin to dynamically generated selects for months, days, and years.
PHP
5
star
76

gastropod

Simple library for generating slugs
Ruby
5
star
77

talking-heads

The creepy talking head app.
JavaScript
5
star
78

bode

The bode webserver, written in C
C
5
star
79

washi

A simple, backbone inspired view helper.
JavaScript
5
star
80

microcosm-preact

Microcosm bindings for Preact:
4
star
81

romanize

Roman numeral conversion programming exercise
Ruby
4
star
82

Search-Words

Ruby
4
star
83

inline-svg-sprite

Inlines external svgs sprites and updates `xlink:href` attributes in `<use>` tags to reference the inlined svg.
JavaScript
4
star
84

Style-and-Swatch-Palettes

4
star
85

microcosm-devtools

Developer tools for Microcosm
3
star
86

lights-out

New programming challenge based a game from the 80s
Ruby
3
star
87

VL_CP_Logger

ExpressionEngine extension that logs more actions to the control panel log.
PHP
3
star
88

dnsimple

Python module for interacting with DNSimple service
Python
3
star
89

Device-Asset-Templates

3
star
90

duke-colab-course

Arduino
3
star
91

json-feed-validator

HTML
3
star
92

responsive-page-text

Mixins for LESS and Sass to make all page text β€”font sizes and line heightsβ€” responsive
CSS
3
star
93

webpack-intro

Intro to Webpacks in Steps
JavaScript
3
star
94

elixir-deploy-quickstart

Quickstart docs and files to get an Elixir app running on production
Elixir
3
star
95

lights-out-vr

A WebVR exploration of Lights Out.
JavaScript
3
star
96

snakey-table-ios

πŸ“± Custom UITableViewCells in iOS
Swift
3
star
97

microcosm-debugger

No longer in service. Use https://github.com/vigetlabs/microcosm-devtools
JavaScript
2
star
98

stimulus-controllers

Astro
2
star
99

gather-content-api

PHP Client for GatherContent API
PHP
2
star
100

wordpress-site-starter

JavaScript
2
star