This project is archived and is in readonly mode.

#5262 ✓resolved
fakingfantastic

Calling #method on new AR objects

Reported by fakingfantastic | July 31st, 2010 @ 03:22 PM

(brought up by PointMan in #rubyonrails)

With Ruby, we can use #method to do something like this:

class Foo
  def hello
    put "hello"
  end
end

foo = Foo.new
foo.method(:hello).call
# => hello

Doing that with an AR object doesn't fire exactly the same way

class User < ActiveRecord::Base
  # has an attr :email from a migration
end

u = User.new
u.method(:email).call

NameError: undefined method `email' for class `User'
    from (irb):2:in `method'
    from (irb):2
    from /Users/franklakatos/.rvm/gems/ruby-1.9.2-head/gems/railties-3.0.0.rc/lib/rails/commands/console.rb:44:in `start'
    from /Users/franklakatos/.rvm/gems/ruby-1.9.2-head/gems/railties-3.0.0.rc/lib/rails/commands/console.rb:8:in `start'
    from /Users/franklakatos/.rvm/gems/ruby-1.9.2-head/gems/railties-3.0.0.rc/lib/rails/commands.rb:23:in `<top (required)>'
    from script/rails:10:in `require'
    from script/rails:10:in `<main>'

This however, will work:

u = User.new
u.email
# => nil
u.method(:email).call
# => nil

I'm doing a little digging now, but I'm assuming Rails doesn't eager load the attributes onto the class until it needs to (because it'd have to hit the DB to set up all the attr values). Not sure if it's a bug, but some may find it breaks a flow of Ruby programming they are used to.

Ruby 1.9.2-head, Rails 3.0.0.rc

Holla atcha boy and let me know

Comments and changes to this ticket

Create your profile

Help contribute to this project by taking a few moments to create your personal profile. Create your profile »

<h2 style="font-size: 14px">Tickets have moved to Github</h2>

The new ticket tracker is available at <a href="https://github.com/rails/rails/issues">https://github.com/rails/rails/issues</a>

Referenced by

Pages