Mark Daggett's Blog

Innovator & Bricoleur

Rails Protip: hash.slice

Rails has hidden gems just waiting to be discovered. I will demonstrate the use of Hash.slice, which is one of the core extensions of ActiveSupport.

Here is an example of how Hash.slice can clean up a controller, take this existing code for example:

1
2
3
def index
  @users = User.paginate({ :page => params[:page].present? ? params[:page].to_i : 1, :per_page => params[:per_page].present? ? params[:per_page].to_i : 12 })
end

With Hash.slice we can shorten it to:

1
2
3
def index
  @users = User.paginate({ :page => 1, :per_page => 12 }.merge(params.slice(:page, :per_page)))
end

Hash.slice is that it is very forgiving. The method only returns the attributes if they exist. In our example we are assured all conditions will be met because the default values will only be overwritten if Hash.slice returns them.

Like this post, then you'll love my book on JavaScript.

Expert JavaScript is your definitive guide to understanding how and why JavaScript behaves the way it does. Master the inner workings of JavaScript by learning in detail how modern applications are made. In covering lesser-understood aspects of this powerful language and truly understanding how it works, your JavaScript code and programming skills will improve.

Comments