Skip to content

Instantly share code, notes, and snippets.

@romchambe
Last active May 29, 2018 13:06
Show Gist options
  • Save romchambe/b80c377f8614369658222e07ec0c9c3e to your computer and use it in GitHub Desktop.
Save romchambe/b80c377f8614369658222e07ec0c9c3e to your computer and use it in GitHub Desktop.
Setup of a Rails app

Setup of a Rails app

Checklists

Rails app initialisation checklist

  1. Create a new Rails app: $ rails new my_app
    • add --api flag to create an API-only application
    • add -T to exclude Minitest as default testing framework
    • add --database=postgresql to use Postgre
  2. Modify Gemfile and install gems: $ bundle install
  3. Install rspec: rails g rspec:install
  4. In config/environments/production.rb, uncomment the following line to force all communications between local browsers and remote servers to have SSL in production (NB: this works only with a Heroku domain, but for another domain, refer to Heroku SSL docs):
config.force_ssl = true
  1. Production webserver: by default, Heroku uses a pure-Ruby webserver called WEBrick, which is easy to set up and run but isn’t good at handling significant traffic. As a result, WEBrick isn’t suitable for production use, so we need to replace WEBrick with Puma. Puma is included by default in Rails 5, so we just need to replace the content of config/puma.rb by:
#config/puma.rb
workers Integer(ENV['WEB_CONCURRENCY'] || 2)
threads_count = Integer(ENV['RAILS_MAX_THREADS'] || 5)
threads threads_count, threads_count

preload_app!

rackup      DefaultRackup
port        ENV['PORT']     || 3000
environment ENV['RACK_ENV'] || 'development'

on_worker_boot do
  # Worker specific setup for Rails 4.1+
  # See: https://devcenter.heroku.com/articles/
  # deploying-rails-applications-with-the-puma-web-server#on-worker-boot
  ActiveRecord::Base.establish_connection
end

and to create Procfile in the root directory of the app and insert the line:

web: bundle exec puma -C config/puma.rb
  1. Commit

Optional

  • Launch the local server: $ rails server
  • Run a first test with a 'Hello world" app => rails g controller home index, then in config/routes.rb set the root as root 'home#index'
  • Configure the generators (what files are generated by the generate command in the command line) in config/application.rb:
#Don't generate helper files associated to controllers
config.generators.helper = false
#Don't generate asset files associated to controllers
config.generators.assets = false
  • Commit

Optional-end

  1. Create an heroku app : $ heroku create
  2. Push on Heroku to make sure that there are no deployment issues in the bas app: $ git push heroku master
  3. Initialize a new Postgre database in development by running: rails db:create. The file config/database.yml should have the following form:
default: &default
  adapter: postgresql
  encoding: unicode
  # For details on connection pooling, see Rails configuration guide
  # http://guides.rubyonrails.org/configuring.html#database-pooling
  pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>

development:
  <<: *default
  database: [YOUR_DATABASE_NAME]
  host: localhost

Assets

application.scss

In this file, the extension needs to be changed to .scss from the original .css. You need to import bootstrap files (coming from the gem), and then all the scss files that will be created in the application:

@import "bootstrap";
@import "custom";

NB: Remove all the *= require and *= require_tree statements from the Sass file. Instead, use @import to import Sass files. Do not use *= require in Sass or your other stylesheets will not be able to access the Bootstrap mixins and variables.

application.js

Bootstrap tooltips and popovers depend on popper.js for positioning. The bootstrap gem already depends on the popper_js gem.

Add Bootstrap dependencies and Bootstrap to your application.js:

//= require jquery3
//= require popper
//= require bootstrap-sprockets

NB:

  • Either bootstrap-sprockets or bootstrap can be required: bootstrap-sprockets provides individual Bootstrap Javascript files (alert.js or dropdown.js, for example), while bootstrap provides a concatenated file containing all Bootstrap Javascripts.

A few other resources

Tests with RSpec

  1. Add to the Gemfile:
group :development, :test do
  gem 'rspec-rails', '~> 3.5'
end

group :test do
  gem 'factory_bot_rails', '~> 4.0'
end
  1. Run rails g rspec:install
  2. If using FactoryBot, $mkdir spec/factories in the newly created spec folder
  3. In spec/rails_helper.rb, add the following lines to set up the different libraries:
RSpec.configuration do |config|
  # [...]
  # add `FactoryBot` methods
  config.include FactoryBot::Syntax::Methods
end

Some layouts

In rails, flash messages are stored in a hash that must be added in the HTML and can be accessed this way:

<div class="container">
   <% flash.each do |key, value| %>
      <div class="alert alert-<%= key %>"><%= value %></div>
   <% end %>
</div>

It will be styled the bootstrap way with this code.

bcrypt

bcryptis the hash function that turns a password into a crypted hash to be stored in DB. It can be used by adding the method has_secure_password to a model. It will generate:

  • The ability to save a securely hashed password_digest attribute to the database
  • A pair of virtual attributes18 (password and password_confirmation), including presence validations upon object creation and a validation requiring that they match
  • An authenticate method that returns the user when the password is correct (and false otherwise)

Asset pipeline

  • To load assets in vendor or lib, these folders need to have in their working tree at least one of the following (or more depeding on your needs): assets/stylesheets, assets/javascripts, assets/images. This is needed so that they are added to the Sprockets load paths and can be required from application.css et application.js files in app/assets. The files placed in it must have a plain .css or .js extension.
  • In the base setup, only the assets available from from application.css et application.js will be compiled. This is due to the 2 lines in app/views/layouts/application.html.erb:
<%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track': 'reload' %>
<%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>
  • In order to compile specific assets, they need to be specifically mentioned in the header of the view where they are supposed to be served.
  • RoR will only compile the asset files starting with application by default in production. In order to have other files compiled in production, the following line needs to be added in initializers/assets.rb:
Rails.application.config.assets.precompile += %w( name_of_asset_file.extension other_asset_file.extension )

Other

  • VALID_LINK_REGEX = /(^$)|(^(http|https):\/\/[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(([0-9]{1,5})?\/.*)?$)/ix
  • Google Analytics tag (UA parameter links the site to your GA account so it must be adapted):
<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-114626786-1"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());
  gtag('config', 'UA-114626786-1');
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment