Last Updated: February 25, 2016
·
665
· heavysixer

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:

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:

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.