:green_book: Russian Version: A community-driven Rails 3 & 4 & 5 style guide.
:green_book: Russian Version: A community-driven Rails 3 & 4 & 5 style guide.
= The Rails Style Guide :idprefix: :idseparator: - :sectanchors: :sectlinks: :toc: preamble :toclevels: 1 ifndef::backend-pdf[] :toc-title: pass:[ Table of Contents ] endif::[] :source-highlighter: rouge
== Introduction
[quote]
Role models are important.
-- Officer Alex J. Murphy / RoboCop
ifdef::env-github[] TIP: You can find a beautiful version of this guide with much improved navigation at https://rails.rubystyle.guide. endif::[]
The goal of this guide is to present a set of best practices and style prescriptions for Ruby on Rails 4 development. It's a complementary guide to the already existing community-driven https://github.com/rubocop-hq/ruby-style-guide[Ruby coding style guide].
This Rails style guide recommends best practices so that real-world Rails programmers can write code that can be maintained by other real-world Rails programmers. A style guide that reflects real-world usage gets used, and a style guide that holds to an ideal that has been rejected by the people it is supposed to help risks not getting used at all - no matter how good it is.
The guide is separated into several sections of related rules. I've tried to add the rationale behind the rules (if it's omitted I've assumed it's pretty obvious).
I didn't come up with all the rules out of nowhere - they are mostly based on my extensive career as a professional software engineer, feedback and suggestions from members of the Rails community and various highly regarded Rails programming resources.
NOTE: Some of the advice here is applicable only to Rails 4.0+.
You can generate a PDF copy of this guide using https://asciidoctor.org/docs/asciidoctor-pdf/[AsciiDoctor PDF], and an HTML copy https://asciidoctor.org/docs/convert-documents/#converting-a-document-to-html[with] https://asciidoctor.org/#installation[AsciiDoctor] using the following commands:
asciidoctor-pdf -a allow-uri-read README.adoc
Install the rouge gem to get nice syntax highlighting in the generated document.
====
Translations of the guide are available in the following languages:
TIP: https://github.com/rubocop-hq/rubocop[RuboCop], a static code analyzer (linter) and formatter, has a https://github.com/rubocop-hq/rubocop-rails[`rubocop-rails`] extension, based on this style guide.
== Configuration
=== Config Initializers [[config-initializers]]
Put custom initialization code in config/initializers.
The code in initializers executes on application startup.
=== Gem Initializers [[gem-initializers]]
Keep initialization code for each gem in a separate file with the same name as the gem, for example carrierwave.rb, active_admin.rb, etc.
=== Dev/Test/Prod Configs [[dev-test-prod-configs]]
Adjust accordingly the settings for development, test and production environment (in the corresponding files under config/environments/)
Mark additional assets for precompilation (if any):
=== App Config [[app-config]]
Keep configuration that's applicable to all environments in the config/application.rb file.
=== Load Rails Config Defaults [[config-defaults]]
When upgrading to a newer Rails version, your application's configuration setting will remain on the previous version. To take advantage of the latest recommended Rails practices, the config.load_defaults setting should match your Rails version.
=== Staging Like Prod [[staging-like-prod]]
Avoid creating additional environment configurations than the defaults of development, test and production.
If you need a production-like environment such as staging, use environment variables for configuration options.
=== YAML Config [[yaml-config]]
Keep any additional configuration in YAML files under the config/ directory.
Since Rails 4.2 YAML configuration files can be easily loaded with the new config_for method:
== Routing
=== Member Collection Routes [[member-collection-routes]]
When you need to add more actions to a RESTful resource (do you really need them at all?) use member and collection routes.
get 'subscriptions/:id/unsubscribe' resources :subscriptions
resources :subscriptions do get 'unsubscribe', on: :member end
get 'photos/search' resources :photos
=== Many Member Collection Routes [[many-member-collection-routes]]
If you need to define multiple member/collection routes use the alternative block syntax.
resources :subscriptions do member do get 'unsubscribe' # more routes end end
resources :photos do collection do get 'search' # more routes end
=== Nested Routes [[nested-routes]]
Use nested routes to express better the relationship between Active Record models.
class Post
", type: :erb end end
class ProductsController { where(active: true) } scope :inactive, -> { where(active: false) }
=== Named Scope Class [[named-scope-class]]
When a named scope defined with a lambda and parameters becomes too complicated, it is preferable to make a class method instead which serves the same purpose of the named scope and returns an ActiveRecord::Relation object.
Arguably you can define even simpler scopes like this.
class User 21').each do |person| person.party_all_night! end
Person.find_each do |person| person.do_awesome_stuff end
=== before_destroy [[before_destroy]]
Since https://github.com/rails/rails/issues/3458[Rails creates callbacks for dependent associations], always call before_destroy callbacks that perform validation with prepend: true.
has_many :roles, dependent: :destroy
before_destroy :ensure_deletable
def ensure_deletable raise "Cannot delete super admin." if super_admin? end
has_many :roles, dependent: :destroy
before_destroy :ensure_deletable, prepend: true
=== has_many/has_one Dependent Option [[has_many-has_one-dependent-option]]
Define the dependent option to the has_many and has_one associations.
class Post = ? AND created_at = :start_date AND created_at { order(id: :asc) }
=== pluck
Use https://api.rubyonrails.org/classes/ActiveRecord/Calculations.html#method-i-pluck[pluck] to select a single value from multiple records.
User.all.map(&:name)
User.all.map { |user| user[:name] }
=== pick
Use https://api.rubyonrails.org/classes/ActiveRecord/Calculations.html#method-i-pick[pick] to select a single value from a single record.
User.pluck(:name).first
User.first.name
=== ids [[ids]]
Favor the use of ids over pluck(:id).
User.pluck(:id)
=== Squished Heredocs [[squished-heredocs]]
When specifying an explicit query in a method such as find_by_sql, use heredocs with squish.
This allows you to legibly format the SQL with line breaks and indentations, while supporting syntax highlighting in many tools (including GitHub, Atom, and RubyMine).
User.find_by_sql(.rb
class ModifyDefaultStatusForProducts
== Internationalization
=== Locale Texts [[locale-texts]]
No strings or other locale specific settings should be used in the views, models and controllers.
These texts should be moved to the locale files in the config/locales directory.
=== Translated Labels [[translated-labels]]
When the labels of an Active Record model need to be translated, use the activerecord scope:
en: activerecord: models: user: Member attributes: user: name: 'Full name'
Then User.model_name.human will return "Member" and User.human_attribute_name("name") will return "Full name".
These translations of the attributes will be used as labels in the views.
=== Organize Locale Files [[organize-locale-files]]
Separate the texts used in the views from translations of Active Record attributes.
Place the locale files for the models in a folder locales/models and the texts used in the views in folder locales/views.
When organization of the locale files is done with additional directories, these directories must be described in the application.rb file in order to be loaded.
=== Shared Localization [[shared-localization]]
Place the shared localization options, such as date or currency formats, in files under the root of the locales directory.
=== Short I18n [[short-i18n]]
Use the short form of the I18n methods: I18n.t instead of I18n.translate and I18n.l instead of I18n.localize.
=== Lazy Lookup [[lazy-lookup]]
Use "lazy" lookup for the texts used in views. Let's say we have the following structure:
en: users: show: title: 'User details page'
The value for users.show.title can be looked up in the template app/views/users/show.html.haml like this:
=== Dot-separated Keys [[dot-separated-keys]]
Use the dot-separated keys in the controllers and models instead of specifying the :scope option.
The dot-separated call is easier to read and trace the hierarchy.
I18n.t :record_invalid, scope: [:activerecord, :errors, :messages]
=== I18n Guides [[i18n-guides]]
More detailed information about the Rails I18n can be found in the https://guides.rubyonrails.org/i18n.html[Rails Guides]
== Assets
Use the https://guides.rubyonrails.org/asset_pipeline.html[asset pipeline] to leverage organization within your application.
=== Reserve app/assets [[reserve-app-assets]]
Reserve app/assets for custom stylesheets, javascripts, or images.
=== lib/assets [[lib-assets]]
Use lib/assets for your own libraries that don't really fit into the scope of the application.
=== vendor/assets [[vendor-assets]]
Third party code such as https://jquery.com/[jQuery] or https://twitter.github.com/bootstrap/[bootstrap] should be placed in `vendor/a
No open issues yet, or sync has not completed.