A Developer with a Pencil

Simple and Easy Getter for Your Models

Here is a little trick we use at ShinobiDevs when we need a quick getter method in our models.

We simply extend our models with a double brackets method, just like a Hash or an Array:

user.rb
1
2
3
4
5
class User < ActiveRecord::Base
  def self.[](id)
    self.where(id: id).first
  end
end

And use it:

1
2
3
4
5
eladmeidar@Elads-MacBook-Pro:~/projects/dummy (master *)$ rails c
Loading development environment (Rails 4.0.0)
[1] pry(main)> User[1]
  User Load (7.9ms)  SELECT `users`.* FROM `users` WHERE `users`.`id` = 1 LIMIT 1
=> #<User id: 1, email: "elad@testing.com"......>

Simple!

Some more use cases

As many people suggested, there is no real difference between using User.find(id) and User[id]. A much better use is to bind this getter to an attribute that isn’t the primary key for that model, for example - username

user.rb
1
2
3
4
5
class User < ActiveRecord::Base
  def self.[](username)
    self.where(username: username).first
  end
end

It is also a reasonable idea to use it with other finder methods:

user.rb
1
2
3
4
5
6
7
class User < ActiveRecord::Base

  # Grab the latest x users, specified by the limit parameter
  def self.[](limit)
    self.limit(limit).order("id DESC")
  end
end

This concept is aimed to provide a shorter syntax for a quick, common getter - I wouldn’t recommend doing something utterly clobbered in this method (conditionals and switches for example).

Comments