Modelos de rieles extensibles

Rails models come with certain built-in methods like this:

Appointment.new
Appointment.find(1)

How do I add more methods to Appointment? It's apparently not done by adding methods to app/models/appointment.rb. Doing that adds methods to an ejemplo of Appointment, but I want to add methods to Appointment itself. How do I do that?

preguntado el 08 de enero de 11 a las 21:01

btw, the term you're looking for is "class methods" (as opposed to "instance methods"). -

Okay, thanks. I was wondering what that was. -

MyClass.new is how you initiate a standard Ruby class instance btw, it has nothing to do with Rails. -

2 Respuestas

def self.some_method
  #do stuff
end

Respondido el 09 de enero de 11 a las 00:01

In case you want to investigate further: They are called "class methods" or "static methods", depending on the language you came from (or both, if you come from python). - FlorianH

Mark's answer is definitely right, but you will also see the following syntax when defining class methods:

class Appointment
  class << self
    def method1
      # stuff
    end

    def method2
      # stuff
    end

    def method3
      # stuff
    end
  end
end

Respondido el 09 de enero de 11 a las 05:01

Is there any benefit from doing it this way though? Cause it seems like a horribly confusing way otherwise; class << self makes no sense at all! - Ashley Williams

@Ashley I can think of at least two benefits of this syntax. 1) You don't have to write self before every method if you have a bunch of class methods and 2) All your class methods are indented and grouped together. Anything is confusing if you've never seen it before, but it's definitely used by a lot of Ruby devs. Here it is in the Rails active record source: github.com/rails/rails/blob/master/activerecord/lib/… - Peter Brown

I've indeed seen this practice a lot (and shamelessly used it once or twice before myself), but it still seems strange, almost a language hack like [*$<], which while perfectly valid, is unnecessarily cryptic, especially in open-source code where you want outsiders to understand and embrace it. Ruby's an elegant language the majority of the time, it seems such a shame to spoil it with overly-smart code such as this where it can be helped. - Ashley Williams

A must read about class << self : yehudakatz.com/2009/11/15/… - DGM

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.