Undefined method IS defined in login subsystem

Hello Taylor,

For some reason my login controller refuses to access a method
i have defined for another class. This is remedial stuff but my
searches haven't cleared up the issue. It is creating the model
but can't access the method. The method is NOT protected or
private. Any thoughts? The error:

  undefined method `try_to_login' for #<Person:0x37ed3f0>

[...]

      #take user object and 'try to log in' (see person model)
      logged_in_person = @person.try_to_login

You're calling #try_to_login as an instance method of @person instance.

[...]

class Person < ActiveRecord::Base

[...]

  def self.try_to_login
    Person.login(self.name, self.password)
  end

You've defined #try_to_login as a class method. Furthermore
inside the #try_to_login code, self.name and self.password will
be calls to class methods Person#name and Person#password
and not instance methods.

So maybe you have to change #try_to_login to be an
instance method.

   -- Jean-François.

Hi --

My understanding was that all class instances inherit all class methods.
'Programming Ruby, 2nd Edition' seems to validate this. Am I wrong?
How can I define an 'instance method' separate from the class? Thanks!

class C
   def m
   end
end

m is an instance method. I'm not sure whether that addresses your
question, though. Can you expand a bit on the problem?

David

Hi --

David,

I have your book! It is a great intro to ruby and it taught me a lot!

Thanks.

But obviously, not enough :frowning:

Whoops :slight_smile:

Back to the question:

try_to_login is clearly a public instance method of Person. @person is
clearly an instance of Person. So why does @person.try_to_login fail
with 'undefined method `try_to_login' for #<Person:0x37ed3f0>?'

You'll need to show some code. There's something going on that's
impossible to pinpoint otherwise.

David

Hello Taylor,

try_to_login is clearly a public instance method of Person.

No it isn't. See your code :

class Person < ActiveRecord::Base
  # ...
  def self.try_to_login
    Person.login(self.name, self.password)
  end
end

@person is clearly an instance of Person.

Yes.

So why does @person.try_to_login fail with 'undefined method
`try_to_login' for #<Person:0x37ed3f0>?'

Because as I said earlier, you defined try_to_login as a class
method. If you don't believe me, read again the chapter about
instance methods/class methods from David's book :slight_smile:

   -- Jean-François.

No, try_to_login is a public class method of Person. This is a class method:

   class Person
     def self.blah
       ...
     end
   end

which you would call as Person.blah.

This is an instance method:

   class Person
     def blah
       ...
     end
   end

which you would call as:

   person = Person.new
   person.blah

You're trying to call the try_to_login class method that you've defined on an instance of Person, which doesn't work.

Pete Yandell
http://aliencamel.com/