Re: Calling a method on class creation

dang
Fri, 24 Aug 2007 00:18:29 -0000

initialize or after_initialize should do what you need. Initialize is
called by ruby when the object is, well, initialized...

cheers,
Dan

================================class User < ActiveRecord::Base
  has_and_belongs_to_many :roles

  def initialize
    evaluate_status
  end

  def evaluate_status
    #evaluate the status
    #@status = ...
  end
end
================================


On Aug 24, 9:15 am, eggie5
<egg...-Re5JQEeQqe8AvxtiuMwx3w@public.gmane.org>
wrote:
> I have a model User that has property called status. Status is just a
> string that can only be evaluated and not persisted. I.e. it
doesn''t
> have a field in the user table.
>
> Anyways, I would like a method get_status to be called anytime I
> create a new instance of User. For example:
>
> user=User.new
>
> Since I created a new instance of User, I should now have access to
> the status property, e.g.:
>
> user.status
> =>"Ready"
>
> Here is my User class:
>
> class User < ActiveRecord::Base
>   has_and_belongs_to_many :roles
>
> def evaluate_status
>     #evaluate the status
>     #@status = ...
>   end
> end
>
> How would I call get_status whenever a new instance of User is
> created? It''s constructor?
>
> Thanks