On Sep 6, 7:00 am, pipplo <joe.kos...@gmail.com> wrote: > Hi Guys, > > I'm experimenting with my first rails app currently. One thing I'm > trying to implement is a login system. > > I created a model for user.rb I've added a couple of functions to the > class for example: > > def self.authenticate(user_info) > find_by_username_and_password(...., > self.hashed_password(user_info[:password])) > end > > def self.hashed_password(password) > Digest::SHA2.hexdigest(password) > end > > So from user.rb function self.authenticate I can call > self.hashed_password and it works fine. > > From another file (user_controller.rb) I try to create a new user > based on the authentication parameters, and then call authenticate on > that user. In order to do that I have to call > user_into.class.authenticate instead of user_info.authenticate... > > I don't understand what is going on here with def self.{function} and > the .class modifier. > > Can someone point to me somewhere to explain? I have a feeling I'm > doing something wrong but I don't understand what. > In the context of a class def self.foo creates a class methods (more generally it is used to create singleton methods).
Calling foo or self.foo tries to call a foo method on the current object - it won't call a class method if you're currently in an instance method, because self is an actual user. You can call class methods by writing User.foo, rather than writing User.foo, you can instead write self.class.foo (assuming that self.class is User) - it's a little more explicit and neater too (eg if the code is inside a module that could be included in many models etc...). Once you're inside a class method like authenticate then self is the class so you can write self.hashed_password or even just hashed_password (self.class.hashed_password would try to call the method on Class itself, which wouldn't work) Fred Fred Fred > Thanks -- You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group. To post to this group, send email to rubyonrails-t...@googlegroups.com. To unsubscribe from this group, send email to rubyonrails-talk+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en.