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?
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With