🛤️ Ruby on Rails

Updated at 2016-01-07 20:44

This guide contains notes how to write Ruby on Rails code.

Related to:


Always use foreman or forego to start the app. Especially if your projects depends on various external processes. Foreman reads .env file for environmental variables and starts all processes listed in Procfile.

gem install foreman
# create Procfile to Rails project root for your webserver
foreman start
foreman start -f
foreman run rake my:custom:task

Remember that Rails caches a lot of things. If something seems off during development, try clearing caches.

# bundle exec rails console

Use try. try will return nil of the receiver object doesn't exist.

# bad if @person if @person && @person.spouse

# good

# try! is the same but will cause NoMethodError if receiver is not nil
# and doesn't contain the tried method

# when working with hashes, lookup method is called `:[]`
@session.try(:[], :comments).try(:[], 10).try(:[], 'value')

Understand Ruby on Rails file structure. Note that all of the files and directories don't necessarily exist or are loaded by default, but these are all very common in Rails apps.

.env                 # process environmental variables for foreman and dotenv
.ruby-version        # Ruby version for rvm and rbenv
Gemfile              # gem dependencies and Ruby version for some tools
Gemfile.lock         # syncs exact gem versions between environments
Rakefile             # automatically loads tasks that can be run command line            # links your Rails app to Rack web server interface
app/                 # all your application specific files
app/assets/          # your own unprocessed images, JavaScript, styles etc.
app/controllers/     # controllers act based on web requests
app/concerns/        # provide functionality to a whole class
app/decorators/      # provide functionality to a class instance
app/mailers/         # handle sending mails
app/helpers/         # provide common methods for controllers, models and views
app/models/          # wrap data, define database mapping and used validations
app/uploaders/       # handle receiving files
app/validators/      # define validations for objects, database-linked or not
app/views/           # HTML templates compiled to respond to the requests
app/workers/         # handle background processes like act of sending email
config/              # configurations for each environment
config/initializers/ # code that is run on app startup
config/locales       # translations by language and localization by country
bin/                 # server-level executables, old 'scripts' directory
db/                  # database schema, migrations and seeds
lib/                 # your non-Rails non-gem code, usually just has rake tasks
log/                 # message logs for each environment
public/              # publicly accessible static files are stored here
spec/                # your RSpec style tests
test/                # your mocks, unit tests, fixtures and functional tests
tmp/                 # temporary files that can be cleared on restart
vendor/              # all non-gem third party code and assets


Main configuration goes to config/application.rb.

Environment specific configuration goes in config/environments. Sometimes it makes sense to create more environments than the 3 default ones.

development.rb  # Default
production.rb   # Default
test.rb         # Used when running tests, default.
triage.rb       # Local development setup that connects to production database.

Your current execution environment is specified by RAILS_ENV environmental variable. It should default to production without anything specified for security reasons.

# .env

Try to keep all .yml configuration files in config/ root. Makes easier to use them.


Put custom initialization code to config/initializers. These are run on application startup.

Name initialization file the same as the related gem. You may add different initialization configuration by environment. Don't create separate files per environment here.

# config/intializers/gemname.rb
if Rails.env.development?
    # ...
    # ...

Don't include any passwords or secrets in version control. Set all production secret values to environment variables. config/secrets.yml is a good place to store accessors for sensitive values.

  secret_key_base: 9ac2d0ad8ebcc312090e99d745006d3cf8
  email_provider_password: <%= ENV["EMAIL_PROVIDER_PASSWORD"] %>

  secret_key_base: a1580ad61ccb6ac60f9f256948cf63d6e20
  email_provider_password: <%= ENV["EMAIL_PROVIDER_PASSWORD"] %>

  secret_key_base: <%= ENV["SECRET_KEY_BASE"] %>
  email_provider_password: <%= ENV["EMAIL_PROVIDER_PASSWORD"] %>
# a lot prettier than ENV["EMAIL_PROVIDER_PASSWORD"]


Use the assets pipeline to leverage organization within your application.

  • Reserve app/assets for custom stylesheets, JavaScripts or images.
  • Use lib/assets for your own libraries that don’t really fit into the scope of the application.
  • Third party code such as jQuery should be placed in vendor/assets.
  • Use Rails Assets for third party front-end libraries.
  • When possible, use gemified versions of assets.