• Stars
    star
    714
  • Rank 60,884 (Top 2 %)
  • Language
    Ruby
  • License
    MIT License
  • Created over 9 years ago
  • Updated about 2 months ago

Reviews

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

Repository Details

Unify your EmberCLI and Rails Workflows

Ember CLI Rails

Unify your EmberCLI and Rails Workflows!

EmberCLI-Rails is designed to give you the best of both worlds:

  • Stay up to date with the latest JavaScript technology and EmberCLI addons
  • Develop your Rails API and Ember front-ends from within a single process
  • Inject Rails-generated content into your EmberCLI application
  • Avoid Cross-Origin Resource Sharing gotchas by serving your EmberCLI applications and your API from a single domain
  • Write truly end-to-end integration tests, exercising your application's entire stack through JavaScript-enabled Capybara tests
  • Deploy your entire suite of applications to Heroku with a single git push

If you're having trouble, checkout the example project!

EmberCLI-Rails Supports EmberCLI 1.13.13 and later.

Install

Add the following to your Gemfile:

gem "ember-cli-rails"

Then run bundle install:

$ bundle install

If you haven't created an Ember application yet, generate a new one:

$ ember new frontend --skip-git

Setup

First, generate the gem's initializer:

$ rails generate ember:init

This will create the following initializer:

# config/initializers/ember.rb

EmberCli.configure do |c|
  c.app :frontend
end

This initializer assumes that your Ember application exists in Rails.root.join("frontend").

If this is not the case, you could

  • move your existing Ember application into Rails.root.join("frontend")
  • configure frontend to reference the Ember application in its current directory:
c.app :frontend, path: "~/projects/my-ember-app"

Initializer options

  • name - this represents the name of the Ember CLI application.

  • path - the path where your Ember CLI application is located. The default value is the name of your app in the Rails root.

  • silent - this provides --silent option for Ember CLI commands to control verbosity of their output.

  • yarn - enables the yarn package manager when installing dependencies

EmberCli.configure do |c|
  c.app :adminpanel # path defaults to `Rails.root.join("adminpanel")`
  c.app :frontend,
    path: "/path/to/your/ember-cli-app/on/disk"
  c.app :payments, silent: true # by default it's false
end

Next, install the ember-cli-rails-addon:

$ cd path/to/frontend
$ ember install ember-cli-rails-addon

Be sure that the addon's MAJOR and MINOR version matches the gem's MAJOR and MINOR versions.

For instance, if you're using the 0.6.x version of the gem, specify ~> 0.6.0 in your Ember app's package.json:

{
  "devDependencies": {
    "ember-cli-rails-addon": "~> 0.6.0"
  }
}

Mount

Configure Rails to route requests to the frontend Ember application:

# config/routes.rb

Rails.application.routes.draw do
  mount_ember_app :frontend, to: "/"
end

Routing options

  • to - The path to handle as an Ember application. This will only apply to format: :html requests. Additionally, this will handle child routes as well. For instance, mounting mount_ember_app :frontend, to: "/frontend" will handle a format: :html request to /frontend/posts. Note: If you specify a custom path, you must also update the rootURL in frontend/config/environment.js. See Mounting multiple Ember applications for more information.
  • controller - Defaults to "ember_cli/ember"
  • action - Defaults to "index"

Finally, install your Ember application's dependencies:

$ rake ember:install

Boot your Rails application, navigate to "/", and view your EmberCLI application!

Develop

EmberCLI Rails exposes several useful rake tasks.

ember:install

Install the Ember applications' dependencies.

ember:compile

Compile the Ember applications.

ember:test

Execute Ember's test suite.

If you're using Rake to run the test suite, make sure to configure your test task to depend on ember:test.

For example, to configure a bare rake command to run both RSpec and Ember test suites, configure the default task to depend on both spec and ember:test.

task default: [:spec, "ember:test"]

Deploy

When Rails is running in production mode, EmberCLI-Rails stops doing runtime compilation. Instead, configured apps are built during rake assets:precompile. This keeps things quick for end users, and extends the normal Rails asset building process.

Configuration information, including instructions for Heroku and Capistrano, can be found below.

CDN

In production environments, assets should be served over a Content Delivery Network.

Configuring an ember-cli-rails application to serve Ember's assets over a CDN is very similar to configuring an EmberCLI application to serve assets over a CDN:

var app = new EmberApp({
  fingerprint: {
    prepend: 'https://cdn.example.com/'
  }
});

If you're serving the Ember application from a path other than "/", the prepend URL must end with the mounted path:

var app = new EmberApp({
  fingerprint: {
    // for an Ember application mounted to `/admin_panel/`
    prepend: 'https://cdn.example.com/admin_panel/',
  }
});

As long as your CDN is configured to pull from your Rails application , your assets will be served over the CDN.

Deployment Strategies

By default, EmberCLI-Rails uses a file-based deployment strategy that depends on the output of ember build.

Using this deployment strategy, Rails will serve the index.html file and other assets that ember build produces.

These EmberCLI-generated assets are served with the same Cache-Control headers as Rails' other static files:

# config/environments/production.rb
Rails.application.configure do
  # serve static files with cache headers set to expire in 1 year
  config.static_cache_control = "public, max-age=31622400"
end

If you need to override this behavior (for instance, if you're using ember-cli-deploy's "Lightning Fast Deployment" strategy in production), you can specify the strategy's class in the initializer:

EmberCli.configure do |config|
  config.app :frontend, deploy: { production: EmberCli::Deploy::Redis }
end

This example configures the frontend Ember application to retrieve the index's HTML from an ember-cli-deploy-redis -populated Redis entry using the ember-cli-rails-deploy-redis gem.

If you're deploying HTML with a custom strategy in development or test, disable EmberCLI-Rails' build step by setting ENV["SKIP_EMBER"] = true.

NOTE:

Specifying a deployment strategy is only supported for applications that use the mount_ember_app and render_ember_app helpers.

Heroku

To configure your EmberCLI-Rails applications for Heroku:

  1. Execute rails generate ember:heroku.
  2. Commit the newly generated files.
  3. Add the NodeJS buildpack and configure NPM to include the bower dependency's executable file (if your build process requires bower).
$ heroku buildpacks:clear
$ heroku buildpacks:add --index 1 heroku/nodejs
$ heroku buildpacks:add --index 2 heroku/ruby
$ heroku config:unset SKIP_EMBER

You are ready to deploy:

$ git push heroku master

EmberCLI compilation happens at deploy-time, triggered by the asset:precompile rake task.

NOTE Run the generator each time you introduce additional EmberCLI applications into the project.

Slug size

Heroku slug size is limited. The build process creates artifacts that are not necessary for the server to run, but are included in the deployed Heroku slug.

Omitting these build assets can dramatically reduce slug size.

A build-pack solution for this is discussed in Issue #491.

Capistrano

EmberCLI-Rails executes both npm install and bower install during EmberCLI's compilation, triggered by the asset:precompile rake task.

The npm and bower executables are required to be defined in the deployment SSH session's $PATH. It is not sufficient to modify the session's $PATH in a .bash_profile.

To resolve this issue, prepend the Node installation's bin directory to the target system's $PATH:

#config/deploy/production.rb

set :default_env, {
  "PATH" => "/home/deploy/.nvm/versions/node/v4.2.1/bin:$PATH"
}

The system in this example is using nvm to configure the node version. If you're not using nvm, make sure the string you prepend to the $PATH variable contains the directory or directories that contain the bower and npm executables.

For faster deployments

Place the following in your deploy/<environment>.rb

set :linked_dirs, %w{<ember-app-name>/node_modules <ember-app-name>/bower_components}

to avoid rebuilding all the node modules and bower components with every deploy. Replace <ember-app-name> with the name of your ember app (default is frontend).

Override

By default, routes defined by ember_app will be rendered with the internal EmberCli::EmberController.

Overriding the view

The EmberCli::EmberController renders the Ember application's index.html and injects the Rails-generated CSRF tags into the <head>.

To customize the view, create app/views/ember_cli/ember/index.html.erb:

<%= render_ember_app ember_app do |head| %>
  <% head.append do %>
    <%= csrf_meta_tags %>
  <% end %>
<% end %>

The ember_app helper is available within the EmberCli::EmberController's view, and refers to the name of the current EmberCLI application.

To inject the EmberCLI generated index.html, use the render_ember_app helper in your view:

<!-- app/views/application/index.html.erb -->
<%= render_ember_app :frontend do |head, body| %>
  <% head.append do %>
    <%= csrf_meta_tags %>
  <% end %>

  <% body.append do %>
    <%= render partial: "my-analytics" %>
  <% end %>
<% end %>

The body block argument and the corresponding call to body.append in the example are both optional, and can be omitted.

Serving Rails-generated CSS

For more information on how to work with EmberCLI-generated stylesheets, refer to the Stylesheets section. EmberCLI-generated CSS will be embedded in the response's HTML document by default.

To serve assets generated and served by Rails, inject them into the document's <head>:

<%= render_ember_app :frontend do |head| %>
  <% head.append do %>
    <%= stylesheet_link_tag "application" %>
    <%= csrf_meta_tags %>
  <% end %>
<% end %>

There are no technical limitations to sharing assets between the Ember client and the Rails server, but picking one or the other might simplify the project's organization.

Sharing code during asset compilation is not possible.

For example, Ember's SCSS files cannot use @import directives referencing Rails' SCSS modules.

Overriding the controller

To override this behavior, you can specify [any of Rails' routing options] route-options.

For the sake of this example, override the controller and action options:

# config/routes.rb

Rails.application.routes.draw do
  mount_ember_app :frontend, to: "/", controller: "application", action: "index"
end

When serving the EmberCLI generated index.html with the render_ember_app helper, make sure the controller's layout is disabled, as EmberCLI generates a fully-formed HTML document:

# app/controllers/application.rb
class ApplicationController < ActionController::Base
  def index
    render layout: false
  end
end

Rendering the EmberCLI generated JS and CSS

Rendering EmberCLI applications with render_ember_app is the recommended, actively supported method of serving EmberCLI applications.

However, for the sake of backwards compatibility, ember-cli-rails supports injecting the EmberCLI-generated assets into an existing Rails layout.

Following the example above, configure the mounted EmberCLI application to be served by a custom controller (ApplicationController, in this case).

In the corresponding view, use the asset helpers:

<%= include_ember_script_tags :frontend %>
<%= include_ember_stylesheet_tags :frontend %>

Mounting multiple Ember applications

Rendering Ember applications to paths other than / requires additional configuration.

Consider a scenario where you had Ember applications named frontend and admin_panel, served from / and /admin_panel respectively.

First, specify the Ember applications in the initializer:

EmberCli.configure do |c|
  c.app :frontend
  c.app :admin_panel, path: "path/to/admin_ember_app"
end

Next, mount the applications alongside the rest of Rails' routes. Note that admin_panel route is added before the frontend route because it's more specific:

# /config/routes.rb
Rails.application.routes.draw do
  mount_ember_app :admin_panel, to: "/admin_panel"
  mount_ember_app :frontend, to: "/"
end

Then set each Ember application's rootURL to the mount point:

// frontend/config/environment.js

module.exports = function(environment) {
  var ENV = {
    modulePrefix: 'frontend',
    environment: environment,
    rootURL: '/',
    // ...
  }
};

// path/to/admin_ember_app/config/environment.js

module.exports = function(environment) {
  var ENV = {
    modulePrefix: 'admin_panel',
    environment: environment,
    rootURL: '/admin_panel',  // originally '/'
    // ...
  }
};

Finally, configure EmberCLI's fingerprinting to prepend the mount point to the application's assets:

// frontend/ember-cli-build.js

module.exports = function(defaults) {
  var app = new EmberApp(defaults, {
    fingerprint: {
      // matches the `/` mount point
      prepend: 'https://cdn.example.com/',
    }
  });
};


// path/to/admin_ember_app/ember-cli-build.js

module.exports = function(defaults) {
  var app = new EmberApp(defaults, {
    fingerprint: {
      // matches the `/admin_panel` mount point
      prepend: 'https://cdn.example.com/admin_panel/',
    }
  });
};

When injecting the EmberCLI-generated assets with the include_ember_script_tags and include_ember_stylesheet_tags helpers to a path other than "/", a <base> tag must also be injected with a corresponding href value:

<base href="/">
<%= include_ember_script_tags :frontend %>
<%= include_ember_stylesheet_tags :frontend %>

<base href="/admin_panel/">
<%= include_ember_script_tags :admin_panel %>
<%= include_ember_stylesheet_tags :admin_panel %>

If you're using the include_ember style helpers with a single-page Ember application that defers routing to the Rails application, insert a call to mount_ember_assets at the bottom of your routes file to serve the EmberCLI-generated assets:

# config/routes.rb
Rails.application.routes.draw do
  mount_ember_assets :frontend, to: "/"
end

CSRF Tokens

Your Rails controllers, by default, expect a valid authenticity token to be submitted along with non-GET requests.

Without the authenticity token, requests will respond with 422 Unprocessable Entity errors (specifically ActionController::InvalidAuthenticityToken).

To add the necessary tokens to requests, inject the csrf_meta_tags into the template:

<!-- app/views/application/index.html.erb -->
<%= render_ember_app :frontend do |head| %>
  <% head.append do %>
    <%= csrf_meta_tags %>
  <% end %>
<% end %>

The default EmberCli::EmberController and the default view handle behave like this by default.

If an Ember application is mounted with another controller, it should append the CSRF tags to its view's <head>.

ember-cli-rails-addon configures your Ember application to make HTTP requests with the injected CSRF tokens in the X-CSRF-TOKEN header.

Serving from multi-process servers in development

If you're using a multi-process server (Puma, Unicorn, etc.) in development, make sure it's configured to run a single worker process.

Without restricting the server to a single process, it is possible for multiple EmberCLI runners to clobber each others' work.

SKIP_EMBER

If set on the environment, SKIP_EMBER will configure ember-cli-rails to skip the build step entirely. This is useful if you're using an alternative deployment strategy in the test or development environment. By default, ember-cli-rails will skip the build step in production-like environments.

EMBER_ENV

If set on the environment, the value of EMBER_ENV will be passed to the ember process as the value of the --environment flag.

If EMBER_ENV is unspecified, the current Rails environment will be passed to the ember process, with the exception of non-standard Rails environments, which will be replaced with production.

RAILS_ENV

While being managed by EmberCLI Rails, EmberCLI process will have access to the RAILS_ENV environment variable. This can be helpful to detect the Rails environment from within the EmberCLI process.

This can be useful to determine whether or not EmberCLI is running in its own standalone process or being managed by Rails.

For example, to enable ember-cli-mirage API responses in development while being run outside of Rails (while run by ember serve), check for the absence of the RAILS_ENV environment variable:

// config/environment.js
if (environment === 'development') {
  ENV['ember-cli-mirage'] = {
    enabled: typeof process.env.RAILS_ENV === 'undefined',
  }
}

RAILS_ENV will be absent in production builds.

EmberCLI support

This project supports:

  • EmberCLI versions >= 1.13.13

Ruby and Rails support

This project supports:

  • Ruby versions >= 2.5.0
  • Rails versions >=5.2.x.

To learn more about supported versions and upgrades, read the upgrading guide.

Contributing

See the CONTRIBUTING document. Thank you, contributors!

License

Open source templates are Copyright (c) 2015 thoughtbot, inc. It contains free software that may be redistributed under the terms specified in the LICENSE file.

About

ember-cli-rails was originally created by Pavel Pravosud and Jonathan Jackson.

ember-cli-rails is maintained by Sean Doyle and Jonathan Jackson.

thoughtbot

ember-cli-rails is maintained and funded by thoughtbot, inc. The names and logos for thoughtbot are trademarks of thoughtbot, inc.

We love open source software! See our other projects or hire us to help build your product.

More Repositories

1

guides

A guide for programming in style.
Ruby
9,327
star
2

bourbon

A Lightweight Sass Tool Set
Ruby
9,100
star
3

paperclip

Easy file attachment management for ActiveRecord
Ruby
9,055
star
4

laptop

A shell script to set up a macOS laptop for web and mobile development.
Shell
8,416
star
5

dotfiles

A set of vim, zsh, git, and tmux configuration files.
Shell
7,864
star
6

factory_bot

A library for setting up Ruby objects as test data.
Ruby
7,826
star
7

administrate

A Rails engine that helps you put together a super-flexible admin dashboard.
JavaScript
5,797
star
8

neat

A fluid and flexible grid Sass framework
Ruby
4,444
star
9

suspenders

A Rails template with our standard defaults, ready to deploy to Heroku.
Ruby
3,922
star
10

til

Today I Learned
3,903
star
11

clearance

Rails authentication with email & password.
Ruby
3,629
star
12

Argo

Functional JSON parsing library for Swift
Swift
3,495
star
13

shoulda-matchers

Simple one-liner tests for common Rails functionality
Ruby
3,469
star
14

high_voltage

Easily include static pages in your Rails app.
Ruby
3,141
star
15

rcm

rc file (dotfile) management
Perl
2,990
star
16

factory_bot_rails

Factory Bot ♥ Rails
Ruby
2,972
star
17

shoulda

Makes tests easy on the fingers and the eyes
Ruby
2,184
star
18

expandable-recycler-view

Custom Android RecyclerViewAdapters that collapse and expand
Java
2,073
star
19

capybara-webkit

A Capybara driver for headless WebKit to test JavaScript web apps
Ruby
1,976
star
20

gitsh

An interactive shell for git
Ruby
1,957
star
21

Tropos

Weather and Forecasts for Humans
Swift
1,518
star
22

refills

[no longer maintained]
CSS
1,513
star
23

design-sprint

Product Design Sprint Material
1,415
star
24

bitters

Add a dash of pre-defined style to your Bourbon.
HTML
1,398
star
25

griddler

Simplify receiving email in Rails
Ruby
1,375
star
26

trail-map

Trails to help designers and developers learn various topics.
1,219
star
27

appraisal

A Ruby library for testing your library against different versions of dependencies.
Ruby
1,194
star
28

hotwire-example-template

A collection of branches that transmit HTML over the wire.
Ruby
989
star
29

parity

Shell commands for development, staging, and production parity for Heroku apps
Ruby
882
star
30

Runes

Infix operators for monadic functions in Swift
Swift
829
star
31

cocaine

A small library for doing (command) lines.
Ruby
788
star
32

fishery

A library for setting up JavaScript objects as test data
TypeScript
759
star
33

flutie

View helpers for Rails applications
Ruby
730
star
34

TBAnnotationClustering

Example App: How To Efficiently Display Large Amounts of Data on iOS Maps
Objective-C
728
star
35

vim-rspec

Run Rspec specs from Vim
Vim Script
650
star
36

climate_control

Modify your ENV
Ruby
512
star
37

constable

Better company announcements
Elixir
511
star
38

carnival

An unobtrusive, developer-friendly way to add comments
Haskell
501
star
39

ruby-science

The reference for writing fantastic Rails applications
Ruby
494
star
40

Curry

Swift implementations for function currying
Swift
493
star
41

pacecar

Generated scopes for ActiveRecord classes
Ruby
437
star
42

hoptoad_notifier

Reports exceptions to Hoptoad
Ruby
408
star
43

fake_stripe

A Stripe fake so that you can avoid hitting Stripe servers in tests.
Ruby
393
star
44

json_matchers

Validate your JSON APIs
Ruby
381
star
45

Swish

Nothing but Net(working)
Swift
364
star
46

paul_revere

A library for "one off" announcements in Rails apps.
Ruby
298
star
47

stencil

Android library, written exclusively in kotlin, for animating the path created from text
Kotlin
282
star
48

Perform

Easy dependency injection for storyboard segues
Swift
280
star
49

superglue

A productive library for Classic Rails, React and Redux
JavaScript
275
star
50

upcase

Sharpen your programming skills.
Ruby
275
star
51

testing-rails

Source code for the Testing Rails book
HTML
269
star
52

proteus

[no longer maintained]
Ruby
254
star
53

Delta

Managing state is hard. Delta aims to make it simple.
Swift
246
star
54

foundry

Providing a new generation of vector assets and infinite possibility for the interactive web and mobile applications
CSS
233
star
55

limerick_rake

A collection of useful rake tasks.
Ruby
232
star
56

backbone-support

lumbar support
JavaScript
227
star
57

shoulda-context

Shoulda Context makes it easy to write understandable and maintainable tests under Minitest and Test::Unit within Rails projects or plain Ruby projects.
Ruby
219
star
58

terrapin

Run shell commands safely, even with user-supplied values
Ruby
216
star
59

Superb

Pluggable HTTP authentication for Swift.
Swift
203
star
60

jack_up

[DEPRECATED] Easy AJAX file uploading in Rails
Ruby
202
star
61

fistface

DIY @font-face web service.
Ruby
182
star
62

squirrel

Natural-looking Finder Queries for ActiveRecord
Ruby
178
star
63

sortable_table

Sort HTML tables in your Rails app.
Ruby
157
star
64

write-yourself-a-roguelike

Write Yourself A Roguelike: Ruby Edition
Ruby
155
star
65

pester

Automatically ask for a PR review
Ruby
147
star
66

jester

REST in Javascript
JavaScript
146
star
67

complexity

A command line tool to identify complex code
Rust
142
star
68

kumade

Heroku deploy tasks with test coverage (DEPRECATED, NO LONGER BEING DEVELOPED)
Ruby
137
star
69

proteus-middleman

[no longer maintained]
CSS
133
star
70

FunctionalJSON-swift

Swift
133
star
71

capybara_discoball

Spin up an external server just for Capybara
Ruby
128
star
72

tropos-android

Weather and Forecasts for Humans
Kotlin
128
star
73

ModalPresentationView

Remove the boilerplate of modal presentations in SwiftUI
Swift
125
star
74

react-native-typescript-styles-example

A template react native project for ergonomic styling structure and patterns.
TypeScript
123
star
75

vimulator

A JavaScript Vim simulator for demonstrations
JavaScript
119
star
76

bourne

[DEPRECATED] Adds test spies to mocha.
Ruby
114
star
77

formulator

A form library for Phoenix
Elixir
106
star
78

poppins

Gifs!
Objective-C
106
star
79

tailwindcss-aria-attributes

TailwindCSS variants for aria-* attributes
JavaScript
100
star
80

ghost-theme-template

A project scaffold for building ghost themes using gulp, node-sass, & autoprefixer
HTML
91
star
81

paperclip_demo

Paperclip demo application
Ruby
87
star
82

middleman-template

The base Middleman application used at thoughtbot, ready to deploy to Netlify.
CSS
86
star
83

proteus-jekyll

[no longer maintained]
CSS
84
star
84

report_card

metrics and CI are for A students.
Ruby
77
star
85

ios-sample-blender

Sample code for the Blending Modes blog post
Objective-C
76
star
86

yuri-ita

Create powerful interfaces for filtering, searching, and sorting collections of items.
Ruby
76
star
87

baccano

[no longer maintained]
HTML
74
star
88

goal-oriented-git

A practical book about using Git
HTML
73
star
89

ios-on-rails

A guide to building a Rails API and iOS app
HTML
72
star
90

art_vandelay

Art Vandelay is an importer/exporter for Rails 6.0 and higher.
Ruby
71
star
91

maybe_haskell

Programming without Null
HTML
71
star
92

redbird

A Redis adapter for Plug.Session
Elixir
67
star
93

maintaining-open-source-projects

A successful open source project is not only one that is original, solves a particular problem well, or has pristine code quality. Those are but the tip of the iceberg, which we'll thoroughly dissect with this book.
Shell
67
star
94

templates

Documentation templates for open source projects.
64
star
95

FOMObot

A slack bot to help with FOMO.
Haskell
61
star
96

BotKit

BotKit is a Cocoa Touch static library for use in iOS projects. It includes a number of helpful classes and categories that are useful during the development of an iOS application.
Objective-C
61
star
97

react-native-template

Template React Native project to be used with Cookiecutter
JavaScript
60
star
98

CombineViewModel

An implementation of the Model-View-ViewModel (MVVM) pattern using Combine.
Swift
59
star
99

flightdeck

Terraform modules for rapidly building production-grade Kubernetes clusters following SRE practices
HCL
55
star
100

design-for-developers-starter-kit

A starter project for design for developer students
CSS
54
star