Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Define a class (instance)method in rails console

Is there any way to define a method for a class instance in the console?

e.g.

 def Model.old?
   self.created_at < Time.now - 35.years
 end

And then run it with

Model.find(1).old?
like image 283
Carpela Avatar asked Aug 14 '15 21:08

Carpela


People also ask

How do you define a class method in Ruby?

There are two standard approaches for defining class method in Ruby. The first one is the “def self. method” (let's call it Style #1), and the second one is the “class << self” (let's call it Style #2). Both of them have pros and cons.

What is instance method in Rails?

In Ruby, a method provides functionality to an Object. A class method provides functionality to a class itself, while an instance method provides functionality to one instance of a class. Consider the following Ruby class: class SayHello def self.


1 Answers

Based on the code you provided, this should be what you want:

class Model
  def old?
    created_at < 35.years.ago
  end
end

You just need to enter each line into the console one by one.

P.S. - Your comparison logic is backwards, so I flipped it back around.

like image 200
dhouty Avatar answered Oct 16 '22 13:10

dhouty