Ruby code guidelines

 https://gist.github.com/tusharsrms/6aefb0990e3990d3ad6104d01c7ba00f


..........................................


Code Review Guidelines for Ruby On Rails
General Guidelines to follow during Development / Reviewing Project.
Directory Structure of the Project.
Use UTF-8 as the source file encoding.
Use two spaces per indentation level (aka soft tabs). No hard tabs.
Commit Messages should be self explanatory the changes made.
Avoid large changes in single commit.
Proper File Headers and Method Headers should be placed in all files.
Method Headers must include parameters list and return type.
External Libraries must be used with proper versioning. (if any)
Use spaces around operators, after commas, colons and semicolons, around { and before }.
No spaces after (, [. No spaces before ], ).
Methods can take a maximum of 4 parameters.
Use empty lines between method definitions and also to break up methods into logical paragraphs internally.
Naming Conventions must be strictly followed. (Except for critical cases.)
Name identifiers in English only.
Choose descriptive names.
Spell words correctly.
Use correct grammar.
Use snake_case for symbols, methods and variables.
Use CamelCase for classes and modules.
Use snake_case for naming files, e.g. hello_world.rb.
Use snake_case for naming directories, e.g. lib/hello_world/hello_world.rb.
Aim to have just a single class/module per source file. Name the file name as the class/module, but replacing CamelCase with snake_case.
Use SCREAMING_SNAKE_CASE for other constants.
The names of predicate methods (methods that return a boolean value) should end in a question mark. (i.e. Array#empty?).
Comments should be properly written and well explanatory.
Prefer to remove code by deleting it over removing it by commenting it out. It shall live forever in source control, and can be retrieved therefrom if it is ever again called upon.
Keep existing comments up-to-date. An outdated comment is worse than no comment at all.
Avoid writing comments to explain bad code. Refactor the code to make it self-explanatory.
TDD(Test Driven Development) or BDD(Behaviour Driven Development) should be followed. (According to the requirement.)
Documentation of Application should be maintained properly.
Source Code Documentation
Documentation of Blocks
Class Documentation
Method Documentation
Test case documentation
Defining the Public API
Overview of Documentation Annotations (Interface Documentation,Class Documentation,Property Documentation,Constructor Documentation,Method Documentation, Test case Documentation)
Exceptions and Error Handling must be implemented wherever necessary.
Ruby Coding Guidelines
Do’s
Aggressively DRY(Don’t Repeat Yourself) code during development.
No space inside range literals.
Prefer map over collect and reduce over inject due to symmetry and familiarity with mapping and reducing in other technologies.
Prefer detect over find and find_all over select to avoid confusion with ActiveRecord and keep select/reject symmetry.
Use _ for unused block parameters. hash.map { |_, v| v + 1 }
Use %() for single-line strings needing interpolation and double-quotes.
Use %w() over ['', ''] for an array of words.
Use && and || for boolean expressions.
Use ||= freely.
Use {...} over do..end for single-line blocks.
Use ! suffix for dangerous methods (modifies self).
Use ? suffix for predicate methods (return a boolean).
Use def with parentheses when there are arguments.
Use do..end over {...} for multi-line blocks.
Use heredocs for multi-line strings.
Use /(?:first|second)/ over /(first|second)/ when you don't need the captured group.
Use private over protected to indicate scope.
Use def self.method over def Class.method or class << self.
Use Set over Array for arrays with unique elements. The lookup is faster.
Use single-quotes for strings unless variable interpolation is required.
Use unless boolean? instead of if !boolean?.
Align the parameters of a method call if they span more than one line. When aligning parameters is not appropriate due to line-length constraints, single indent for the lines after the first is also acceptable.
Indent when as deep as case. This is the style established in both "The Ruby Programming Language" and "Programming Ruby".
Align the elements of array literals spanning multiple lines.
Use def with parentheses when there are parameters. Omit the parentheses when the method doesn't accept any parameters.
Favor unless over if for negative conditions (or control flow ||).
Avoid %q, %Q, %x, %s, and %W.
Avoid conditional modifiers (lines that end with conditionals).
Avoid hashes as optional parameters. Does the method do too much?
Avoid including code and gems in source control that are specific to your development machine or process. Examples: .rvmrc s, file watchers, debuggers.
Avoid meta-programming.
Avoid monkey-patching core classes.
Avoid return unless required.
Avoid superfluous parentheses when calling methods, but keep them when you assign the return value. x = Math.sin(y) array.delete e
Avoid ternary operators (boolean ? true : false). Use multi-line if instead to emphasize code branches.(Optional)
Avoid the use of parallel assignment for defining variables. Parallel assignment is allowed when it is the return of a method call, used with the splat operator, or when used to swap variable assignment. Parallel assignment is less readable than separate assignment.
Don’ts
Don't use parentheses around the condition of an if/unless/while/until.
Do not use while/until condition do for multi-line while/until.
Do not use if x; .... Use the ternary operator instead.
Don't use unless with else.
Do not use for, unless you know exactly why. Most of the time iterators should be used instead. for is implemented in terms of each (so you're adding a level of indirection), but with a twist - for doesn't introduce a new scope (unlike each) and variables defined in its block will be visible outside it.
Rails Coding Guidelines
Do’s
Aim for skinny models and skinny controllers.
Set config.action_mailer.raise_delivery_errors = true in the development environment.
Initialize code in config/initializers.
Put custom initialization code in config/initializers. The code in initializers executes on application startup.
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.
Adjust accordingly the settings for development, test and production environment (in the corresponding files under config/environments/)
Keep the db/schema.rb under version control.
Keep configuration that's applicable to all environments in the config/application.rb file.
Create an additional staging environment that closely resembles the production one.
Limit database defaults to counter caches and booleans.
Limit the number of instance variables shared between controller and view.
Name initializers for their gem name. Example: paperclip.rb
Order controller contents: filters, public methods, private methods.
Order model contents: constants, attributes, associations, nested attributes, named scopes, validations, callbacks, public methods, private methods.
Prefer classes to modules when designing functionality that is shared by multiple models.
Prefer gems over plugins.
Prefer presenters (Ruby objects responsible for presentation) over view helpers.
Put all copy text in models, views, controllers, and mailers in config/locales.
Set config.action_mailer.delivery_method = :test in the test environment.
Use _path over _url for named routes everywhere except mailer views.
Use def self.method over the named_scope :method DSL.
Use Foreman to run Rails apps in development mode.
Use I18n.t 'dot.separated.key' over I18n.t :key, :scope => [:dot, :separated].
Use Haml over erb.
Use has_and_belongs_to_many if all you need is a join table. Start simple.
Use namespaced locale lookup in the views by prefixing a period: t '.title'.
Use nested routes to express belongs_to relationships between resources.
Use one ActionMailer for the app. Name it Mailer.
Use single recipient SMTP in the staging environment.
Use the default render 'partial' syntax over render :partial => 'partial'.
Use the :only option to explicitly state exposed routes.
Avoid the :except option in routes.
Avoid member and collection routes.
Avoid Single Table Inheritance.
Consider extracting private methods to their own object.
Deploy to Heroku.
Don’ts
Don't invoke a model's class directly from a view.
Don't use SQL or SQL fragments (where('inviter_id is not null')) outside of models.
More Details on Best Practises to follow :
References :-
Ruby Style Guide : https://github.com/bbatsov/ruby-style-guide
Rails Style Guide : https://github.com/bbatsov/rails-style-guide

Comments

Popular posts from this blog

Rails 7 Features :: Comparison with Rails 6 and Rails 5