GIANT ROBOTS SMASHING INTO OTHER GIANT ROBOTS

Written by thoughtbot

i did not know that

Here’s something I discovered the other day:

ActiveRecord infers model attributes from the database. Each attribute gets a getter, setter, and query method.

A query method? I know this is true for boolean columns but non boolean columns?


class User < ActiveRecord::Base
end
  users (id, name)

  def test_should_say_if_it_does_or_does_not_have_a_name_when_sent_name?
    user = User.new
    assert ! user.name?

    user.name = ''
    assert ! user.name?

    user.name = 'name'
    assert user.name?
  end

You get that query method for free for each of your ActiveRecord attributes. From this passing test it looks as if for strings its implemented in terms of String#blank?

This is nice because it can save you an extra message.


  if user.name.blank?
  end

becomes


  if ! user.name?
  end