ruk·si

🛤️ Ruby on Rails
Basics

Updated at 2016-01-07 20:44

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

Related to:

General

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 Procfile.dev
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
Rails.cache.clear

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

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

# good
@person.try(:name)
@person.try(:spouse).try(:name)

# 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
config.ru            # 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

Configuration

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
RAILS_ENV=development

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

Rails::Application.config_for(:yaml_file_name)

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?
    # ...
else
    # ...
end

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.

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

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

production:
  secret_key_base: <%= ENV["SECRET_KEY_BASE"] %>
  email_provider_password: <%= ENV["EMAIL_PROVIDER_PASSWORD"] %>
Rails.application.secrets.email_provider_password
# a lot prettier than ENV["EMAIL_PROVIDER_PASSWORD"]

Assets

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.

Sources