Automate code formatting in your rails project

https://www.youtube.com/watch?v=C759shnD97k). The problem here is that we are all still human and we make mistakes, accidentally breaking the standard here or there. So we decided to automate this and finally have a devised a standard way to automate code formatting in our rails project. We will be automating both our ruby code and our JS code, since the marriage between web packer and rails it’s now inevitable to keep JS out of our workflow. The idea devised is to run the auto code check right after we commit the code, in case if there are any issues that can’t be auto-corrected by the system the system should stop the commit. Also, it’s important that the auto-correction runs only on the diff so that we don’t end up confusing the reviewers.   For a legacy project, I suggest doing `bundle exec rubocop –a` and fix the errors before adding this hook.  

How to implement

To implement this we are using husky (https://github.com/typicode/husky) a really nice JS library that helps us build git hooks easily.
yarn add --dev husky
  The second JS library we are going to add is `lint-staged` which limits our formatters to only run on the staged git files (ie. The changes).
yarn add --dev lint-staged
Once these two are installed we can set our system to autorun rubocop by adding the following lines to the package.json.
"scripts": {
    "precommit": "lint-staged"
  },
  "lint-staged": {
   "{app,spec,lib}/**/*.rb": [
      "bundle exec rubocop -a",
      "git add"
    ]
  }
  the above configuration would ensure that our formatters run only inside the app or spec or lib folders. Also please note that since we have the pre commit hook, this code is executed after you typed `git commit –m` but it will get executed before the actual commit happening.  

Auto Formatting Javascript

https://prettier.io/ is an opinionated code formatter that supports many languages, in fact it’s also being extended to ruby. We will be using it to format our javascript code, which internally we are using es6. You can read more about it from its project page.
yarn add --dev prettier
Following which we need to add to the script section of our code:
   "app/**/*.{js,es6,jsx,scss,css}": [
      "./node_modules/prettier/bin-prettier.js --trailing-comma es5 --write",
      "git add"
    ]
The final package.json inside a fresh project would look like this:
{
  "name": "starter",
  "private": true,
  "dependencies": {
    "@rails/webpacker": "^3.3.0"
  },
  "scripts": {
    "precommit": "lint-staged"
  },
  "lint-staged": {
    "app/**/*.{js,es6,jsx,scss,css}": [
      "./node_modules/prettier/bin-prettier.js --trailing-comma es5 --write",
      "git add"
    ],
    "{app,test}/**/*.rb": [
      "bundle exec rubocop -a",
      "git add"
    ]
  },
  "devDependencies": {
    "husky": "^0.13.4",
    "lint-staged": "^3.6.0",
    "prettier": "^1.4.2",
    "webpack-dev-server": "^2.11.1"
  }
}
 ]]>