Developer should know this 5 developing tips for Ruby on Rail

Developing Tips For Ruby Rail

Hash#dig

I didn’t meet this in anybody’s code for a long time of RoR development and found as of late. What’s more, it’s conspicuous why :- ) The main Ruby form I worked with was 1.8, however this technique was presented in 2.3.

How frequently did you accomplish something like this:

… if params[:user] && params[:user][:address] && params[:user][:address][:somewhere_deep]

Consider dig sort of safe navigation operator and. in any case, for Hash objects. So now you could revamp such things:

… if params.dig(:user, :address, :somewhere_deep)

Object#presence_in

This one I found in the great article about Query Objects in Ruby on Rails. It enables you to supplant conditionals (frequently ternary) with single technique call when you don’t really require a boolean consequence of incorporation check, yet a checked protest itself. For instance, your code resembles:

sort_options = [:by_date, :by_title, :by_author]

sort = sort_options.include?(params[:sort])
? params[:sort]
: :by_date
# Another option
sort = (sort_options.include?(params[:sort]) && params[:sort]) || :by_date

Does this look better?

ruby on rails

params[:sort].presence_in(sort_options) || :by_date

Module#alias_attribute

All things considered, I discovered this extremely helpful when I took a shot at a venture with a heritage database. It had a table with odd section names like SERNUM_0, ITMDES1_0 and other. We mapped this table to an ActiveRecord show and as opposed to writing queries and extensions on it like WeirdTable.where(SERNUM_0: ‘123’) , we came up to utilizing alias_attribute since it doesn’t simply create getter and setter (and also a predicate strategy), yet works in queries too:

alias_attribute :name, :ITMDES1_0

scope :by_name, -> (name) { where(name: name) }

Object#presence

This one is more well known than others. There’s truly great clarification on ApiDock. Along these lines, object.presence is equal to:

object.present? ? object : nil

If you want to learn Ruby on Rails from scratch then watch this video below:

Image Source: Freepik