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.
Written by Mark Daggett
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Rails
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#