Rails Best Practices

Post on 28-Jun-2015

140 Views

Category:

Software

1 Downloads

Preview:

Click to see full reader

DESCRIPTION

Rails Best Practices Characteristics of good code 1) Maintainability 2) Readability 3) Flexibility 4) Easy Delegation

Transcript

Rails Best Practices

What’s Good Code?

Good code is like a Good Joke!!

It needs no explanation!!

How to write Good Code?

Follow Best Practices

Characteristics of a good code:

Maintainability

Readability

Flexibility

Easy Delegation

Fat Model, Skinny Controller

SQL InjectionPrevent SQL injection by using ? to set the

params of the query

Bad Practice

Good Practice

N + 1 queries problemConsider the following code which finds 10 clients and prints their postcodes

Total queries executed here are 11. 1 to fine 10clients and then 10(1 per each client to find its address)

Solution to N+1 queries problem

Eager Loading

Use “includes”. With includes, ActiveRecord ensures that all of the specified associations are loaded using minimum possible queries.

Use ScopesBad Practice

Good Practice

Use Query AttributeDo you always check if ActiveRecord’s attributes

exists or are blank? present?

Rails provides a cleaner way by query attribute

Bad Practice

Good Practice

Each attribute of ActiveRecord’s model has a query method, so you don’t need to use present? blank?

Annotate your modelsDon’t go to schema.rb file everytime to find the

table structure information.

We have a easier way. Use gem annotate https://github.com/ctran/annotate_models

It will automatically add comments at the top and bottom of your models to list the table structures information

Use model association

Good Practice

Bad Practice:

Protect Mass Assignment

Problem :

Solution: You can use attr_protected to declare a blacklist of variables you don’t want it to be assigned

DRY CodeDon’t repeat the code in controller. You can

avoid that using before_filter

Eg: Bad practice

Removing repeated codeAs you saw in previous slide, below statement

was repeated in all actions. We can avoid it if we use before filter

Good Practice

Referenceshttp://guides.rubyonrails.org/

http://rails-bestpractices.com/

Gem for code metric tool for rails-projects https://github.com/railsbp/rails_best_practices

Online service to find security issues in rails project http://rails-brakeman.com/

https://github.com/presidentbeef/brakeman

Thank You

Want to join our team.Email your CV athr@paramisoft.com

Want to hire us. Contact us on engage@paramisoft.com

top related