Skip to content

Commit

Permalink
Add Generators
Browse files Browse the repository at this point in the history
Adds a Rails generator for installing everything needed to get up and running.
The generator includes a "Hello World" example that allows the user to see an
example of working code. All examples represent our current best practices
at Shaka Code.

The generator is invoked as follows:

`rails generate react_on_rails:install`

The generator can also be passed several options:

- `--redux` (alias: `-R`): uses Redux in the Hello World example client code
- `--server-rendering` (alias: `S`): include files needed for server rendering

These options can be combined:

`rails generate react_on_rails:install --redux --server-rendering`

All generator code is inside of lib/generators/react_on_rails

All generator specs are included inside of the spec/react_on_rails/generators
folder. These tests will create a dummy folder specifically for testing the generators.
Any files that the generator expects to already be existing when run will need to be
manually created as part of the setup phase for each test.

The install generator relies on several other react_on_rails generators that are
hidden from the user via the special `!hide` command at the beginning of the
generator's definition. These generators are invoked from the install generator
according to the options passed from the user.

Because of the multiple unique combinations of options that can be passed from
the user, it was necessary to split template files into several sub-folders based
on those options. Files common to all builds are inside of the templates/base
folder and files specific to non-redux or redux buildes are in similarly-named
folders. Within each, there may or not be further folders depending
on whether or not the user has chosen to also pass server-rendering as an option.

This commit was the work of several developers:

- Aaron Van Bokhoven (original committer)
- Rob Wise (generator code, enhancments, tests, revisions, documentation)
- Blaine Hatab (bug fixes and revisions)
- Justin Gordon (extensive code reviews, revisions, documentation)

List of partial updates during development of generators:

- Add link to blog post in README
- Implement Redux generation
- Put screenshot of client-side versus server-side react component in README
- Change name of Generator Testing Script to generator_testing_script.md
- do not include other hello world example along with Redux hello world example
- Make 'basic' example demonstrate state'
- Make naming more consistent across different versions of generation
- added prerender false if it isnt built with server rendering
- prevent user from running genertor with uncommitted changes
- Convert no-redux components to es2015 class syntax
- Use 'static' keyword for displayName in redux components
- Avoid using constructor to set initial state in non-redux generator
- Add trailing comma to base webpack config
- added check for development to reload server bundle ever time it changes. changed links in readme from shell to markdown links. moved linters order
- Add heroku_development_generator
- Create a Rails Sass helper file
- Rename pre and post bootstrap partials and improve comments
- Switch to Alex's suggested React syntax and add client readme
- Force git to use capital filenames where appropriate
- Make exception for eslinter for e and _ variables
- Add comment about differing production and dev builds to middleware
- Change Redux alias to -R from -d
- Rearrange README section ordering as directed by JG
- Add styling to post-bootstrap to prove it's working
  • Loading branch information
robwise committed Nov 5, 2015
1 parent 1044c8e commit 6772a4f
Show file tree
Hide file tree
Showing 90 changed files with 5,652 additions and 319 deletions.
1 change: 1 addition & 0 deletions .eslintignore
@@ -1,2 +1,3 @@
node_modules
coverage
spec/react_on_rails/dummy-for-generators
1 change: 1 addition & 0 deletions .eslintrc
Expand Up @@ -14,3 +14,4 @@ rules:
indent: [1, 2, { SwitchCase: 1, VariableDeclarator: 2 }]
react/sort-comp: 0
react/jsx-quotes: 0
id-length: [1, { min: 2, exceptions: [_, e, i, k, v] }]
1 change: 1 addition & 0 deletions .gitignore
Expand Up @@ -16,6 +16,7 @@
/spec/dummy-react-013/app/assets/javascripts/generated/
/spec/dummy-react-013/coverage/
/spec/dummy/coverage/
/spec/react_on_rails/dummy-for-generators/

# RVM
.ruby-version
Expand Down
2 changes: 1 addition & 1 deletion .jscsrc
@@ -1,7 +1,7 @@
{
"preset": "airbnb",
"fileExtensions": [".js", ".jsx"],
"excludeFiles": ["**/build/**", "**/node_modules/**", "**/generated/**", "**/docs/**", "**/tmp/**", "**/sample_generated/**", "**/coverage/**", "**/vendor/**"],
"excludeFiles": ["**/build/**", "**/node_modules/**", "**/generated/**", "**/docs/**", "**/tmp/**", "**/sample_generated/**", "**/coverage/**", "**/vendor/**", "**/dummy-for-generators/**"],
"requireTrailingComma": { "ignoreSingleValue": true, "ignoreSingleLine": true },
"validateQuoteMarks": false
}
1 change: 1 addition & 0 deletions .rubocop.yml
Expand Up @@ -16,6 +16,7 @@ AllCops:
- 'client/node_modules/**/*'
- 'bin/**/*'
- !ruby/regexp /old_and_unused\.rb$/
- 'spec/react_on_rails/dummy-for-generators/**/*'

Metrics/LineLength:
Max: 120
Expand Down
File renamed without changes.
457 changes: 153 additions & 304 deletions README.md

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion Rakefile
Expand Up @@ -4,7 +4,7 @@ require "coveralls/rake/task"
namespace :run_rspec do
desc "Run RSpec for top level only"
task :gem do
sh %( COVERAGE=true rspec spec/react_on_rails_spec.rb )
sh %( COVERAGE=true rspec spec/react_on_rails )
end

desc "Run RSpec for spec/dummy only"
Expand Down
12 changes: 12 additions & 0 deletions docs/Contributing.md
Expand Up @@ -35,6 +35,18 @@ Start the sample app like this for some debug printing:
TRACE_REACT_ON_RAILS=true && foreman start
```

### Install Generator
In your Rails app add this gem with a path to your fork.

```
gem 'react_on_rails', path: '/your_fork'
gem 'therubyracer'
```

The main installer can be run with ```rails generate react_on_rails:install```

### Testing the Generator
The generators are covered by generator tests using Rails's generator testing helpers, but it never hurts to do a sanity check and explore the API. See [generator_testing_script.md](generator_testing_script.md) for a script on how to run the generator on a fresh project.

## Updating New Versions of the Gem

Expand Down
1 change: 0 additions & 1 deletion docs/README.md

This file was deleted.

3 changes: 3 additions & 0 deletions docs/gen-notes/react_syntax.md
@@ -0,0 +1,3 @@
# React Syntax
## Communication Between Components
See https://facebook.github.io/react/tips/communicate-between-components.html
31 changes: 31 additions & 0 deletions docs/gen-notes/reducers.md
@@ -0,0 +1,31 @@
# Reducers
Documentation of generated Redux code for reducers.

## Example
The `helloWorld/reducers/index.jsx` example that results from running the generator with the Redux option may be slightly confusing because of its simplicity. For clarity, what follows is a more fleshed-out example of what a reducer might look like:

```javascript
import usersReducer from './usersReducer';
import blogPostsReducer from './blogPostsReducer';
import commentsReducer from './commentsReducer';
// ...

import { $$initialState as $$usersState } from './usersReducer';
import { $$initialState as $$blogPostsState } from './blogPostsReducer';
import { $$initialState as $$commentsState } from './commentsReducer';
// ...

export default {
$$usersStore: usersReducer,
$$blogPostsStore: blogPostsReducer,
$$commentsStore: commentsReducer,
// ...
};

export const initalStates = {
$$usersState,
$$blogPostsState,
$$commentsState,
// ...
};
```
50 changes: 50 additions & 0 deletions docs/generator_testing_script.md
@@ -0,0 +1,50 @@
Per running steps:
From directory of `react_on_rails`, with a test app named "react_on_rails_gen"

```bash
cd ..
rails new react_on_rails_gen
cd react_on_rails_gen
git init
git add .
git commit -m "Rails new plus react_on_rails"
```
Edit the Gemfile, adding these 2 lines:

```ruby
gem 'react_on_rails', path: '../react_on_rails'
gem 'therubyracer'
```

Note the relative path to the react_on_rails gem.
```bash
bundle
git commit -am "added react_on_rails gem"
```
You can now mess around with the generator:

```bash
# See available options
rails generate react_on_rails:install --help
# Actual install, for example, with Redux
rails generate react_on_rails:install --redux
```

If you do actually run the generator, then you can see the changes that the generator made, ready for a commit.
Then run:
```bash
cd client
npm install
cd ..
foreman start -f Procfile.dev
```
Then visit `localhost:3000/hello_world` to see it.
That's it!
8 changes: 8 additions & 0 deletions docs/linters.md
@@ -0,0 +1,8 @@
# Linters
The React on Rails generator automatically adds linters and their recommended accompanying configurations to your project (to disable this behavior, include the `--skip-linters` option when running the generator). Those linters that are written in Ruby have been added to your Gemfile, and those that run in Node have been add to your `package.json` under `devDependencies`.

To run the linters (runs both Ruby and Node linters):

```bash
rake lint
```
202 changes: 202 additions & 0 deletions docs/manual_configuration.md
@@ -0,0 +1,202 @@
## Manual Installation
Follow these steps if you choose to forgo the generator:

1. Globally expose React in your webpack config like [this](https://github.com/shakacode/react-webpack-rails-tutorial/blob/537c985dc82faee333d80509343ca32a3965f9dd/client/webpack.client.base.config.js#L31):

```javascript
module: {
loaders: [
// React is necessary for the client rendering:
{ test: require.resolve('react'), loader: 'expose?React' },

// For React 0.14
{ test: require.resolve('react-dom'), loader: 'expose?ReactDOM' }, // not in the server one
```
2. Require `react_on_rails` in your `application.js` like [this](https://github.com/shakacode/react-webpack-rails-tutorial/blob/361f4338ebb39a5d3934b00cb6d6fcf494773000/app/assets/javascripts/application.js#L15). It possibly should come after you require `turbolinks`:
```
//= require react_on_rails
```
3. Expose your client globals like [this](https://github.com/shakacode/react-webpack-rails-tutorial/blob/537c985dc82faee333d80509343ca32a3965f9dd/client/app/startup/clientGlobals.jsx#L3):
```javascript
import App from './ClientApp';
window.App = App;
```
4. Put your client globals file as webpack entry points like [this](https://github.com/shakacode/react-webpack-rails-tutorial/blob/537c985dc82faee333d80509343ca32a3965f9dd/client/webpack.client.rails.config.js#L22). Similar pattern for server rendering.
```javascript
config.entry.app.push('./app/startup/clientGlobals');
```
## Additional Steps For Server Rendering (option `prerender` shown below)
See the next section for a sample webpack.server.rails.config.js.
1. Expose your server globals like [this](https://github.com/shakacode/react-webpack-rails-tutorial/blob/537c985dc82faee333d80509343ca32a3965f9dd/client/app/startup/serverGlobals.jsx#L7)
```javascript
import App from './ServerApp';
global.App = App;
```
2. Make the server globals file an entry point in your webpack config, like [this](https://github.com/shakacode/react-webpack-rails-tutorial/blob/537c985dc82faee333d80509343ca32a3965f9dd/client/webpack.server.rails.config.js#L7)
```javascript
entry: ['./app/startup/serverGlobals'],
```
3. Ensure the name of your ouput file (shown [here](https://github.com/shakacode/react-webpack-rails-tutorial/blob/537c985dc82faee333d80509343ca32a3965f9dd/client/webpack.server.rails.config.js#L9)) of your server bundle corresponds to the configuration of the gem. The default path is `app/assets/javascripts/generated`. See below for customization of configuration variables.
4. Expose `React` in your webpack config, like [this](https://github.com/shakacode/react-webpack-rails-tutorial/blob/master/client/webpack.server.rails.config.js#L23)
```javascript
{ test: require.resolve('react'), loader: 'expose?React' },

// For React 0.14
{ test: require.resolve('react-dom/server'), loader: 'expose?ReactDOMServer' }, // not in client one, only server
```
#### Sample webpack.server.rails.config.js (ONLY for server rendering)
Be sure to check out the latest example version of [client/webpack.server.rails.config.js](https://github.com/shakacode/react-webpack-rails-tutorial/blob/master/client/webpack.server.rails.config.js).
```javascript
// Common webpack configuration for server bundle

module.exports = {

// the project dir
context: __dirname,
entry: ['./app/startup/serverGlobals'],
output: {
filename: 'server-bundle.js',
path: '../app/assets/javascripts/generated',

// CRITICAL to set libraryTarget: 'this' for enabling Rails to find the exposed modules IF you
// use the "expose" webpackfunctionality. See startup/serverGlobals.jsx.
// NOTE: This is NOT necessary if you use the syntax of global.MyComponent = MyComponent syntax.
// See http://webpack.github.io/docs/configuration.html#externals for documentation of this option
//libraryTarget: 'this',
},
resolve: {
extensions: ['', '.webpack.js', '.web.js', '.js', '.jsx', 'config.js'],
},
module: {
loaders: [
{test: /\.jsx?$/, loader: 'babel-loader', exclude: /node_modules/},

// React is necessary for the client rendering:
{ test: require.resolve('react'), loader: 'expose?React' },
{ test: require.resolve('react-dom/server'), loader: 'expose?ReactDOMServer' },
],
},
};
```
### What Happens?
Here's what the browser will render with a call to the `react_component` helper.
![2015-09-28_20-24-35](https://cloud.githubusercontent.com/assets/1118459/10157268/41435186-6624-11e5-9341-6fc4cf35ee90.png)
If you're curious as to what the gem generates for the server and client rendering, see [`spec/dummy/client/app/startup/serverGlobals.jsx`](https://github.com/shakacode/react_on_rails/blob/master/spec/dummy/spec/sample_generated_js/server-generated.js)
and [`spec/dummy/client/app/startup/ClientReduxApp.jsx`](https://github.com/shakacode/react_on_rails/blob/master/spec/dummy/spec/sample_generated_js/client-generated.js) for examples of this. Note, this is not the code that you are providing. You can see the client code by viewing the page source.
* **props**: [hash | string of json] Properties to pass to the react object. See this example if you're using Jbuilder: [react-webpack-rails-tutorial view rendering props using jBuilder](https://github.com/shakacode/react-webpack-rails-tutorial/blob/master/app/views/pages/index.html.erb#L20)
```erb
<%= react_component('App', render(template: "/comments/index.json.jbuilder"),
generator_function: true, prerender: true) %>
```
* **options:** [hash]
* **generator_function**: <true/false> default is false, set to true if you want to use a generator function rather than a React Component.
* **prerender**: <true/false> set to false when debugging!
* **trace**: <true/false> set to true to print additional debugging information in the browser default is true for development, off otherwise
* **replay_console**: <true/false> Default is true. False will disable echoing server rendering logs, which can make troubleshooting server rendering difficult.
* Any other options are passed to the content tag, including the id.
## JavaScript
1. Configure your webpack configuration to create the file used for server rendering if you plan to do server rendering.
2. Follow the examples in `spec/dummy/client/app/startup/clientGlobals.jsx` to expose your react components for client side rendering.
```ruby
import HelloWorld from '../components/HelloWorld';
window.HelloWorld = HelloWorld;
```
3. Follow the examples in `spec/dummy/client/app/startup/serverGlobals.jsx` to expose your react components for server side rendering.
```ruby
import HelloWorld from '../components/HelloWorld';
global.HelloWorld = HelloWorld;
```
## Server Rendering Tips
- Your code can't reference `document`. Server side JS execution does not have access to `document`, so jQuery and some
other libs won't work in this environment. You can debug this by putting in `console.log`
statements in your code.
- You can conditionally avoid running code that references document by passing in a boolean prop to your top level react
component. Since the passed in props Hash from the view helper applies to client and server side code, the best way to
do this is to use a generator function.
You might do something like this in some file for your top level component:
```javascript
global.App = () => <MyComponent serverSide={true} />;
```
The point is that you have separate files for top level client or server side, and you pass some extra option indicating that rendering is happening server sie.
## Optional Configuration
Create a file `config/react_on_rails.rb` to override any defaults. If you don't specify this file,
the default options are below.
The `server_bundle_js_file` must correspond to the bundle you want to use for server rendering.
```ruby
# Shown below are the defaults for configuration
ReactOnRails.configure do |config|
# Client bundles are configured in application.js
# Server bundle is a single file for all server rendering of components.
# Set the server_bundle_js_file to "" if you know that you will not be server rendering.
config.server_bundle_js_file = "app/assets/javascripts/generated/server.js" # This is the default

# Below options can be overriden by passing to the helper method.
config.prerender = false # default is false
config.generator_function = false # default is false, meaning that you expose ReactComponents directly
config.trace = Rails.env.development? # default is true for development, off otherwise

# For server rendering. This can be set to false so that server side messages are discarded.
config.replay_console = true # Default is true. Be cautious about turning this off.
config.logging_on_server = true # Default is true. Logs server rendering messags to Rails.logger.info

# Settings for the pool of renderers:
config.server_renderer_pool_size ||= 1 # ExecJS doesn't allow more than one on MRI
config.server_renderer_timeout ||= 20 # seconds
end
```
You can configure your pool of JS virtual machines and specify where it should load code:
- On MRI, use `therubyracer` for the best performance (see [discussion](https://github.com/reactjs/react-rails/pull/290))
- On MRI, you'll get a deadlock with `pool_size` > 1
- If you're using JRuby, you can increase `pool_size` to have real multi-threaded rendering.
## Tips
+ **DO NOT RUN `rails s`** and instead run `foreman start -f Procfile.dev`
+ The default for rendering right now is `prerender: false`. **NOTE:** Server side rendering does not work for some components, namely react-router, that use an async setup for server rendering. You can configure the default for prerender in your config.
+ You can expose either a React component or a function that returns a React component. If you wish to create a React component via a function, rather than simply props, then you need to set the property "generator" on that function to true. When that is done, the function is invoked with a single parameter of "props", and that function should return a React element.
+ Be sure you can first render your react component client only before you try to debug server rendering!
+ Open up the HTML source and take a look at the generated HTML and the JavaScript to see what's going on under the covers. Note that when server rendering is turned on, then you'll see the server rendered react components. When server rendering is turned off, then you'll only see the `div` element where the in-line JavaScript will render the component. You might also notice how the props you pass (a Ruby Hash) becomes in-line JavaScript on the HTML page.

## React 0.13 vs. React 0.14
The main difference for using react_on_rails is that you need to add additional lines in the webpack config files:

+ Normal mode (JavaScript is rendered on the client side) webpack config file:

```javascript
{ test: require.resolve('react-dom'), loader: 'expose?ReactDOM' },
```
+ Server-side rendering webpack config file:

```javascript
{ test: require.resolve('react-dom/server'), loader: 'expose?ReactDOMServer' },
```
29 changes: 29 additions & 0 deletions docs/node_dependencies_and_npm.md
@@ -0,0 +1,29 @@
# Node Dependencies and NPM
## Updating
After installing the files, you may want to update the node dependencies. This is analogous to updating gem versions:

```bash
cd client
npm install -g npm-check-updates
rm npm-shrinkwrap.json
npm-check-updates -u
npm install
npm prune
npm shrinkwrap
```

Confirm that the hot replacement dev server and the Rails server both work. You may have to delete `node_modules` and `npm-shrinkwrap.json` and then run `npm shrinkwrap`.

*Note: `npm prune` is required before running `npm shrinkwrap` to remove dependencies that are no longer needed after doing updates.*

## Adding New Dependencies
Typically, you can add your Node dependencies as you normally would. Occasionally, adding a new dependency may require removing and re-running `npm shrinkwrap`:

```bash
cd client
npm install --save module_name@version
# or
# npm install --save_dev module_name@version
rm npm-shrinkwrap.json
npm shrinkwrap
```

0 comments on commit 6772a4f

Please sign in to comment.