Ruby on Rails

Topics related to Ruby on Rails:

Getting started with Ruby on Rails

logo

Ruby on Rails (RoR), or Rails, is an open-source popular web application framework. Rails uses Ruby, HTML, CSS, and JavaScript to create a web application that runs on a web server. Rails uses the model-view-controller (MVC) pattern and provides a fullstack of libraries from the database all the way to the view.

Routing

"Routing" in general is how URL's are "handled" by your app. In Rails case it's typically which controller and which action of that controller will handle a particular incoming URL. In Rails apps, routes are usually placed in the config/routes.rb file.

ActiveRecord

Views

ActiveRecord Migrations

  • Most migration files live in db/migrate/ directory. They’re identified by a UTC timestamp at the beginning of their file name: YYYYMMDDHHMMSS_create_products.rb.

  • The rails generate command can be shortened to rails g.

  • If a :type is not passed to a field, it defaults to a string.

Rails Best Practices

Naming Conventions

ActionCable

ActionCable was available for Rails 4.x, and was bundled into Rails 5. It allows easy use of websockets for realtime communication between server and client.

ActiveModel

ActiveModel was created to extract the model behavior of ActiveRecord into a separate concern. This allows us to use ActiveModel behavior in any object, not just ActiveRecord models.

ActiveRecord objects include all of this behavior by default.

User Authentication in Rails

At the time of generating devise configs using rails generate devise:install, devise will list out bunch of instructions on the terminal to follow.

If you already have a USER model, running this command rails generate devise USER will append necessary columns to your existing USER model.

Use this helper method before_action :authenticate_user! at the top of your controller to check whether user is logged-in or not. if not then they will be redirected to sign-in page.

ActiveRecord Associations

ActiveRecord Validations

ActiveRecord Query Interface

ActionMailer

It is advisable to process the sending of email asynchronously so as not to tie up your web server. This can be done through various services such as delayed_job.

Rails generate commands

The possible values for 'type' in field:type are:

Data TypeDescription
:stringFor smaller pieces of text (usually has a character limit of 255)
:textFor longer pieces of text, like a paragraph
:binaryStoring data including images, audios and videos
:booleanStoring true or false values
:dateOnly the date
:timeOnly the time
:datetimeDate and time
:floatStoring floats without precision
:decimalStoring floats with precision
:integerStoring whole numbers

Configuration

I18n - Internationalization

Using GoogleMaps with Rails

File Uploads

Caching

ActionController

Configuration

Safe Constantize

Rails 5

Authorization with CanCan

Before using CanCan don't forget to create Users either by devise gem or manually. To get maximum functionality of CanCan do create an Admin user.

Mongoid

Gems

Gemfile documentation

For projects that are expected to grow, it is a good idea add comments your Gemfile. That way, even in large setups you will still know what each gem does even if the name is not self-explanatory and you added it 2 years ago.

This can also help you to remember why you chose a certain version and consequently re-evaluate the version requirement later on.

Examples:

# temporary downgrade for TeamCity
gem 'rake', '~> 10.5.0'
# To upload invoicing information to payment provider
gem 'net-sftp'

Change default timezone

config.active_record.default_timezone determines whether to use Time.local (if set to :local) or Time.utc (if set to :utc) when pulling dates and times from the database. The default is :utc. http://guides.rubyonrails.org/configuring.html


If you want to change Rails timezone, but continue to have Active Record save in the database in UTC, use

# application.rb
config.time_zone = 'Eastern Time (US & Canada)'

If you want to change Rails timezone AND have Active Record store times in this timezone, use

# application.rb
config.time_zone = 'Eastern Time (US & Canada)'
config.active_record.default_timezone = :local

Warning: you really should think twice, even thrice, before saving times in the database in a non-UTC format.

Note
Do not forget to restart your Rails server after modifying application.rb.


Remember that config.active_record.default_timezone can take only two values

  • :local (converts to the timezone defined in config.time_zone)
  • :utc (converts to UTC)

Here's how you can find all available timezones

rake time:zones:all

Asset Pipeline

Upgrading Rails

ActiveRecord Locking

Debugging

Configure Angular with Rails

Rails logger

Prawn PDF

Rails API

Deploying a Rails app on Heroku

ActiveSupport

ActiveSupport is a utility gem of general-purpose tools used by the rest of the Rails framework.

One of the primary ways it provides these tools is by monkeypatching Ruby's native types. These are referred to as Core Extensions.

Form Helpers

  • The date input types including date, datetime, datetime-local, time, month and week do not work in FireFox.
  • input<type="telephone"> only works with Safari 8.
  • input<type="email"> does not work on Safari

ActiveRecord Transactions

Transactions are protective blocks where SQL statements are only permanent if they can all succeed as one atomic action. The classic example is a transfer between two accounts where you can only have a deposit if the withdrawal succeeded and vice versa. Transactions enforce the integrity of the database and guard the data against program errors or database break-downs. So basically you should use transaction blocks whenever you have a number of statements that must be executed together or not at all.

RSpec and Ruby on Rails

Decorator pattern

The Decorator pattern allows you to add or modify behavior of objects in a situational way without affecting the base object.

This can be achieved though plain Ruby using the stdlib, or via popular gems such as Draper.

Elasticsearch

React with Rails using react-rails gem

Rails Cookbook - Advanced rails recipes/learnings and coding techniques

Multipurpose ActiveRecord columns

Class Organization

This seems like a simple thing to do but when you're classes start ballooning in size you'll be thankful you took the time to organize them.

Shallow Routing

Model states: AASM

Rails 5 API Authetication

Testing Rails Applications

Active Jobs

Rails frameworks over the years

Add Admin Panel

Use it if you want to have Admin to your website otherwise there is no need for this. It is more easy and powerful than active_admin gem. You can add this at any stage after creating users and don't forget to make any user admin before the 4th step. Use cancan for granting roles.

Nested form in Ruby on Rails

Factory Girl

Import whole CSV files from specific folder

Tools for Ruby on Rails code optimization and cleanup

ActiveJob

Active Model Serializers

Rails Engine - Modular Rails

Single Table Inheritance

ActiveRecord Transactions

Turbolinks

As a rails developer, you will likely interact minimally with turbolinks during your development. It is, however, an important library to be familiar with because it can be the cause of some hard-to-find bugs.

Key takeaways:

  • Bind to the turbolinks:load event instead of the document.ready event
  • Use the data-turbolinks-false attribute to disable turbolink functionality on a per-link basis.
  • Use the data-turbolinks-permanent attribute to persist elements across page loads and to avoid cache-related bugs.

For a more in-depth treatment of turbolinks, visit the official github repository.

Credit for much of this documentation goes to the folks who drafted the turbolinks documentation on the github repository.

Friendly ID

Securely storing authentication keys

Authenticate Api using Devise

Integrating React.js with Rails Using Hyperloop

Change a default Rails application enviornment

Reserved Words

Rails -Engines

Engines are very good options for creating reusable plugin for rails application

Adding an Amazon RDS to your rails application

Payment feature in rails

Rails on docker