Skip to content

Instantly share code, notes, and snippets.

@sergii
Last active August 29, 2015 14:06
Show Gist options
  • Save sergii/a8f563bc89f0db3a7df0 to your computer and use it in GitHub Desktop.
Save sergii/a8f563bc89f0db3a7df0 to your computer and use it in GitHub Desktop.

Some Rails Best Practices which are really best practices to me

Keep in mind

  1. Single Responsibity Principle (SRP).
  2. Skinny Controller, Fat Model.

Tips

  1. Start a new projet

Controller

  1. Use OpenStruct in your search
  2. Have too many things like post.creatable_by?(user), give cancan a try.
  3. Try to make your app really REST
  4. Tired of keep doing @post = Post.find(post_id) in your actions? Check out decent_exposure

Model

  1. Don't use default_scope in your model

  2. Tired of going to schema.rb to see your table schema? Use annotate gem

  3. Don't check @user.login.blank? again

  4. Prevent SQL Injection by using ? in queries

  5. Follow Law of Demeter, use delegate

  6. Use batched finder to large data query

    Just don't write something like this:

    #Let's say you have 10000 users in your User table
    User.all.each do |user|
        NewsLetter.email(user).deliver
    end

    Use batched finder instead

    User.find_in_batches(:batch_size => 5000) do
        NewsLetter.email(user).deliver
    end
  7. Use all? to check the validity of a collection

View/Partial

  1. Always use local variables in your partial
  2. Use collection on rendering partial

Migrations

  1. When you generate a new migration, double-check by using rake db:migrate, rake db:migrate:redo

Helper

  1. Don't use time_ago_in_words
  2. As a Rubyist, you should always know Enumerable
  3. Pulling your hair with working days? Give business_time a try.
  4. Holidays? There is a gem

I18n

  1. Organising your locales folder
  2. Use Rails Lazy look-up for page_title
  3. Raise missing tranlation errors in your test
  4. Find all missing translations in your app

Route

  1. Wanna have friendly URL, friendly_id can help.
  2. Language switching (http://example.com/en/about-us). Try this

Assets Pipeline

  1. Font doesn't work on Heroku? See this:

Testing

  1. Use rake spec:[controllers|features|models] to run examples in specified directory
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment