Calling ruby method without instantiating class
Asked Answered
L

5

5

If I call a method on a rails active model method like so:

class Foo < ActiveRecord::Base

end

Foo.first

I'll get back the first active record. I don't have to instantiate the class.

But if I create my own class and call a method, I get an exception:

class Person < ActiveRecord::Base
  def greeting
    'hello'
  end
end

Person.greeting 

#EXCEPTION: undefined method `greeting' for Person:Class

How can I make that problem go away?

Loraineloralee answered 25/10, 2012 at 11:43 Comment(2)
FYI, what you have seems like it should almost definitely not be in the model, and instead be in the view or a helper.Vallation
My real world example does something with the data :)Loraineloralee
B
13

There are several kinds of methods. The two most important ones are: instance methods and class instance methods.

Foo.first is a class instance method. It works on a class instance (Foo, in this case). If it stores some data inside the class, that data is shared globally across your program (because there's only one class with name Foo (or ::Foo, to be exact)).

But your greeting method is an instance method, it requires object instance. If your greeting method will use Person's name, for example, it has to be instance method, so that it will be able to use instance data (the name). If it doesn't use any instance-specific state and you really meant it to be a class instance method, then use the self "prefix".

class Person < ActiveRecord::Base
  def self.greeting
    'hello'
  end
end
Bite answered 25/10, 2012 at 11:47 Comment(0)
I
9

Try class methods:

class Person < ActiveRecord::Base
  def self.greeting
    'hello'
  end
end

Or another syntax:

class Person < ActiveRecord::Base
  class << self
    def greeting
      'hello'
    end
  end
end
Interscholastic answered 25/10, 2012 at 11:45 Comment(0)
I
2
class Person < ActiveRecord::Base
  def Person.greeting
    'hello'
  end
end

Will work too. I like it because it is very clear what it does; it will result in an error when you decide to rename the Person class however.

Illfated answered 25/10, 2012 at 16:24 Comment(0)
V
1
class Person < ActiveRecord::Base
    def self.greeting
      'hello'
    end
end
Vivisection answered 25/10, 2012 at 11:46 Comment(0)
B
0

To do a static method try this:

class MyModel
    def self.do_something
        puts "this is a static method"
    end
end

MyModel.do_something  # => "this is a static method"
MyModel::do_something # => "this is a static method"

Brewington answered 25/10, 2012 at 11:51 Comment(1)
Except, you know, there are no static methods in ruby :)Bite

© 2022 - 2024 — McMap. All rights reserved.