Skip to content

# Step 01 — Creating a New Rails Application

Gerald Goh edited this page Sep 12, 2020 · 2 revisions

Create Rails application

$ rails new energy-tracker -T -B -d postgresql --webpack=react --skip-coffee
      create
      create  README.md
      create  Rakefile
.
.
├─ react@16.13.1
└─ scheduler@0.19.1
Done in 6.05s.
  • energy-tracker, installs the required Ruby and JavaScript dependencies, and configures Webpack.

  • The -d flag specifies the preferred database engine, which in this case is PostgreSQL.

  • The --webpack instructs Rails to preconfigure for JavaScript with the webpack bundler, in this case specifically for a React application.

  • The --skip-coffee instructs Rails not to set up CoffeeScript.

Root directory has a number of auto-generated files and folders that make up the structure of a Rails application, including a package.json file containing the dependencies for a React application.

Remove Unnecessary default routes

config/application.rn

require_relative 'boot'

require 'rails/all'

# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)

module EnergyTracker
  class Application < Rails::Application
    # Initialize configuration defaults for originally generated Rails version.
    config.load_defaults 6.0
     # CODE YOU SHOULD ADD vvvvvv
     initializer(:remove_action_mailbox_and_activestorage_routes, after: :add_routing_paths) { |app|
      app.routes_reloader.paths.delete_if {|path| path =~ /activestorage/}
      app.routes_reloader.paths.delete_if {|path| path =~ /actionmailbox/ }
    }

    # Settings in config/environments/* take precedence over those specified here.
    # Application configuration can go into files in config/initializers
    # -- all .rb files in that directory are automatically loaded after loading
    # the framework and any gems in your application.
  end
end

Linter Setup

Clone file content into root directory (except for readme.md)

Install ESLint on Linux environment using the following commands

Install Node Version Manager to update NodeJS + NPM.

$curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.35.2/install.sh | bash

$export NVM_DIR="$([ -z "${XDG_CONFIG_HOME-}" ] && printf %s "${HOME}/.nvm" || printf %s "${XDG_CONFIG_HOME}/nvm")"

$[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh" # This loads nvm

Run the following command to verify installation;

$ command -v 
nvm

To download, compile, and install the latest release of node, do this.

nvm install node

Source here

Please do the following steps in this order:

Set-up Stickler (Github app) - it will show that your app is free from style errors

  1. Install stickler-ci https://github.com/apps/stickler-ci
  2. Enable stickler in your repo. You can do it here.
  3. In first commit of your feature branch add a copy of .stickler.yml and .eslintrc.json to the root directory.
    • Remember to use both files linked above
    • Remember that .stickler.yml file name starts with a dot.
  4. Do not make any changes in config files - they represent style guidelines that you share with your tem - which is a group of all Microverse students.
  5. When you open your first pull request you should see Stickler's report at Checks tab.

Set-up ESlint in your local env - it will help you to find style errors

Go project folder using WSL environment and initiate NPM with following command

$ npm init
This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sensible defaults.

See `npm help json` for definitive documentation on these fields
and exactly what they do.

Use `npm install <pkg>` afterwards to install a package and
save it as a dependency in the package.json file.

Press ^C at any time to quit.
package name: (redux-bookstore)
version: (1.0.0)
description: 
entry point: (webpack.config.js) src/index.js
test command:
git repository: 
keywords:
author: Gerald Goh
license: (ISC)
About to write to /package.json:

{
  "name": "",
  "version": "1.0.0",
  "description": "",
  "main": "src/index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/geraldgsh/energy-tracker.git"
  },
  "author": "Gerald Goh",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/geraldgsh/energy-tracker/issues"
  },
  "homepage": "https://github.com/geraldgsh/energy-tracker#readme"
}

Command above will generate a "package.json" file for ESlint work off from.

Install ESlint with following command

  1. Run npm install eslint eslint-config-airbnb --save-dev (not sure how to use npm? Read this).

  2. Run npx eslint --init.

  3. Make sure you select the following options when prompted.

    ? How would you like to use ESLint? To check syntax, find problems, and enforce code style

    ? What type of modules does your project use? JavaScript modules (import/export)

    ? Which framework does your project use? React

    ? Does your project use Typescript No

    ? Where does your code run? Browser

    ? How would you like to define a style for your project? Use a popular style guide

    ? Which style guide do you want to follow? Airbnb

    ? What format do you want your config file to be in? JSON

    The config that you've selected requires the following dependencies: ? Would you like to install them now with npm? Yes

  4. Copy the contents of .eslintrc.json to the newly generated .eslintrc.json overwritting the previous content.

  5. Do not make any changes in config files - they represent style guidelines that you share with your tem - which is a group of all Microverse students.

  6. Double check your ./src folder for any extra unnecesary .eslint config files that might have been generated as this might cause an issue with stickler when you create your Pull Request later on.

  7. Run npx eslint ..

  8. Fix linter errors.

  9. IMPORTANT NOTE: feel free to research auto-correct options for ESlint if you get a flood of errors but keep in mind that correcting style errors manually will help you to make a habit of writing a clean code!

Set-up Rubocop in your local env - it will help you to find style errors

  1. Add gem 'rubocop' to Gemfile (not sure how to use Gemfile? Read this).
  2. Run bundle install.
  3. Copy .rubocop.yml to the root directory of your project
  4. Do not make any changes in config files - they represent style guidelines that you share with your team - which is a group of all Microverse students.
  5. Run rubocop.
  6. Fix linter errors.
  7. IMPORTANT NOTE: feel free to research auto-correct options for Rubocop if you get a flood of errors but keep in mind that correcting style errors manually will help you to make a habit of writing a clean code!

Troubleshooting

  1. All config files are in my repo but Stickler does not work.

    screenshot

    • Try to add a new commit to your Pull Request. Stickler should detect changes in your repo and start checking your code.
  2. while scanning for the next token found character '\t' that cannot start any token error.

    • Please make sure that you used spaces not tabs for indentation.
  3. Check if someone else has had similar problem before here. Please make sure that you used spaces not tabs for indentation.

  4. Stickler does not work and nothing helps 💥 - run eslint in your local env and correct all errors. Remember to let your Code Reviewer know that you had problems with Stickler and you used linter in local env.

Setup production environment (!Important before Heroku Setup)

/gemfile

group :production do    
    gem 'pg'
    gem 'rails_12factor'
    gem 'heroku-deflater'   
end

Set to true

config/environments/production.rb

config.assets.compile = true

Remove line below;

app/views/layout/application.html.erb

<%= stylesheet_pack_tag 'Application' %>

Ensure it runs i local production

RAILS_ENV=production rake db:create

   (126.6ms)  CREATE TABLE "schema_migrations" ("version" character varying NOT NULL PRIMARY KEY)
   (153.9ms)  CREATE TABLE "ar_internal_metadata" ("key" character varying NOT NULL PRIMARY KEY, "value" character varying, "created_at" timestamp(6) NOT NULL, "updated_at" timestamp(6) NOT NULL)
   (1.0ms)  SELECT pg_try_advisory_lock(364970931234871185)
   (1.5ms)  SELECT "schema_migrations"."version" FROM "schema_migrations" ORDER BY "schema_migrations"."version" ASC
Migrating to CreateUsers (20200507185915)
== 20200507185915 CreateUsers: migrating ======================================
.
.
.
$ rails server -e production
=> Booting Puma
=> Rails 6.0.3 application starting in production
=> Run `rails server --help` for more startup options
Puma starting in single mode...
* Version 4.3.3 (ruby 2.6.5-p114), codename: Mysterious Traveller
* Min threads: 5, max threads: 5
* Environment: production
* Listening on tcp://0.0.0.0:3000
Use Ctrl-C to stop

Precompile all assets. Refer here

$ rake assets:precompile RAILS_ENV=production
[1/4] Resolving packages...
success Already up-to-date.
Done in 0.74s.
yarn install v1.21.1
.
.

Heroku Setup

$ heroku login
heroku: Press any key to open up the browser to login or q to exit:
Opening browser to https://cli-auth.heroku.com/auth/cli/browser/c8c6b705-7da5-4b96-9c58-b11eff16bb1f
heroku: Waiting for login...
Logging in... done
Logged in as ***@***.***

$ heroku create energy-track
Creating energy-track... done
https://energy-track.herokuapp.com/ | https://git.heroku.com/energy-track.git

$ git push heroku feature:master
Enumerating objects: 248, done.
Counting objects: 100% (248/248), done.
Delta compression using up to 8 threads
Compressing objects: 100% (219/219), done.
Writing objects: 100% (248/248), 282.17 KiB | 3.13 MiB/s, done.
Total 248 (delta 79), reused 0 (delta 0)
remote: Compressing source files... done.
remote: Building source:
.
.

Other useful heroku commands

$ git remote -v
heroku  https://git.heroku.com/energy-track.git (fetch)
heroku  https://git.heroku.com/energy-track.git (push)
origin  https://github.com/geraldgsh/energy-tracker.git (fetch)
origin  https://github.com/geraldgsh/energy-tracker.git (push)
$ git remote -v
heroku  https://git.heroku.com/energy-track.git (fetch)
heroku  https://git.heroku.com/energy-track.git (push)
origin  https://github.com/geraldgsh/energy-tracker.git (fetch)
origin  https://github.com/geraldgsh/energy-tracker.git (push)

$ heroku apps:destroy
 »   Warning: heroku update available from 7.35.0 to 7.39.2.
 !    WARNING: This will delete react-calculate including all add-ons.
 !    To proceed, type react-calculate or re-run this command with --confirm
 !    myapp

> myapp
Destroying react-rails-recipebook (including all add-ons)... done

$ sudo apt-get update && sudo apt-get upgrade heroku
[sudo] password for xxxx:
Hit:1 http://archive.ubuntu.com/ubuntu xenial InRelease
Get:2 http://security.ubuntu.com/ubuntu xenial-security InRelease [109 kB]
Get:3 https://cli-assets.heroku.com/apt ./ InRelease [2,879 B]
Hit:4 https://deb.nodesource.com/node_8.x xenial InRelease
Get:5 http://archive.ubuntu.com/ubuntu xenial-updates InRelease [109 kB]
Get:6 https://dl.yarnpkg.com/debian stable InRelease [17.1 kB]
.
.
.

$ heroku apps:rename react-rails-recipebook --app protected-coast-99868
 »   Warning: heroku update available from 7.35.0 to 7.39.2.
Renaming protected-coast-99868 to react-calculate... done
https://react-calculate.herokuapp.com/ | https://git.heroku.com/react-calculate.git
Git remote heroku updated
 !    Don't forget to update git remotes for all other local checkouts of the
 !    app.

DB migration on Heroku

$ heroku run rails assets:precompile
$ heroku run rails assets:create
$ heroku run rails assets:reset
$ heroku run rails db:migrate

Running rails db:migrate on react-rails-recipebook... starting, run.1143 (Free)
Running rails db:migrate on react-rails-recipebook... connecting, run.1143 (Free)
Running rails db:migrate on react-rails-recipebook... up, run.1143 (Free)
D, [2020-04-26T16:19:17.602395 #4] DEBUG -- :    (23.0ms)  CREATE TABLE "schema_migrations" ("version" character varying NOT NULL PRIMARY KEY)
D, [2020-04-26T16:19:17.618859 #4] DEBUG -- :    (12.2ms)  CREATE TABLE "ar_internal_metadata" ("key" character varying NOT NULL PRIMARY KEY, "value" character varying, "created_at" timestamp(6) NOT NULL, "updated_at" timestamp(6) NOT NULL)
D, [2020-04-26T16:19:17.629707 #4] DEBUG -- :    (2.0ms)  SELECT pg_try_advisory_lock(8060784764612748840)
D, [2020-04-26T16:19:17.662292 #4] DEBUG -- :    (1.0ms)  SELECT "schema_migrations"."version" FROM "schema_migrations" ORDER BY "schema_migrations"."version" ASC
I, [2020-04-26T16:19:17.665204 #4]  INFO -- : Migrating to CreateRecipes (20200425194512)
== 20200425194512 CreateRecipes: migrating ====================================
-- create_table(:recipes)
D, [2020-04-26T16:19:17.671822 #4] DEBUG -- :    (0.7ms)  BEGIN
D, [2020-04-26T16:19:17.684430 #4] DEBUG -- :    (10.9ms)  CREATE TABLE "recipes" ("id" bigserial primary key, "name" character varying NOT NULL, "ingredients" text NOT NULL, "instruction" text NOT NULL, "image" character varying DEFAULT 'https://raw.githubusercontent.com/do-community/react_rails_recipe/master/app/assets/images/Sammy_Meal.jpg', "created_at" timestamp(6) NOT NULL, "updated_at" timestamp(6) NOT NULL)
   -> 0.0143s
== 20200425194512 CreateRecipes: migrated (0.0146s) ===========================

D, [2020-04-26T16:19:17.694583 #4] DEBUG -- :   primary::SchemaMigration Create (0.9ms)  INSERT INTO "schema_migrations" ("version") VALUES ($1) RETURNING "version"  [["version", "20200425194512"]]
D, [2020-04-26T16:19:17.696340 #4] DEBUG -- :    (1.4ms)  COMMIT
D, [2020-04-26T16:19:17.716013 #4] DEBUG -- :   ActiveRecord::InternalMetadata Load (4.9ms)  SELECT "ar_internal_metadata".* FROM "ar_internal_metadata" WHERE "ar_internal_metadata"."key" = $1 LIMIT $2  [["key", "environment"], ["LIMIT", 1]]
D, [2020-04-26T16:19:17.733900 #4] DEBUG -- :    (0.7ms)  BEGIN
D, [2020-04-26T16:19:17.735600 #4] DEBUG -- :   ActiveRecord::InternalMetadata Create (1.0ms)  INSERT INTO "ar_internal_metadata" ("key", "value", "created_at", "updated_at") VALUES ($1, $2, $3, $4) RETURNING "key"  [["key", "environment"], ["value", "production"], ["created_at", "2020-04-26 16:19:17.725799"], ["updated_at", "2020-04-26 16:19:17.725799"]]
D, [2020-04-26T16:19:17.742174 #4] DEBUG -- :    (2.3ms)  COMMIT
D, [2020-04-26T16:19:17.744291 #4] DEBUG -- :    (1.3ms)  SELECT pg_advisory_unlock(8060784764612748840)

DB seed on Heroku

$ heroku run rails db:seed

Running rails db:seed on react-rails-recipebook... starting, run.8075 (Free)
Running rails db:seed on react-rails-recipebook... connecting, run.8075 (Free)
Running rails db:seed on react-rails-recipebook... up, run.8075 (Free)
D, [2020-04-26T16:20:07.077894 #4] DEBUG -- :    (1.5ms)  SELECT "schema_migrations"."version" FROM "schema_migrations" ORDER BY "schema_migrations"."version" ASC
.
.
$ heroku run rails s
 »   Warning: heroku update available from 7.40.0 to 7.42.13.
Running rails s on time-tracky... starting, run.9086 (Free)
Running rails s on time-tracky... connecting, run.9086 (Free)
Running rails s on time-tracky... up, run.9086 (Free)
=> Booting Puma
=> Rails 6.0.3.3 application starting in production
=> Run `rails server --help` for more startup options
Puma starting in single mode...
* Version 4.3.6 (ruby 2.6.5-p114), codename: Mysterious Traveller
* Min threads: 5, max threads: 5
* Environment: production
* Listening on tcp://0.0.0.0:33139
$ heroku run rake assets:precompile
Running rake assets:precompile on energy-track... starting, run.5172 (Free)
Running rake assets:precompile on energy-track... connecting, run.5172 (Free)
.
.

Update Heroku

$ heroku update
heroku: Updating CLI...
heroku: Updating CLI from 7.35.0 to 7.39.5...

Other useful Heroku comman

heroku git:remote -a thawing-inlet-61413
set git remote heroku to https://git.heroku.com/thawing-inlet-61413.git