These are class methods or 'singleton' methods. One you should be familiar with is attr_accessor. We can implement something like it in a test class.
class Klass
def self.add_getter_and_setter(symbol)
module_eval "def #{symbol}; @#{symbol}; end"
module_eval "def #{symbol}=(val); @#{symbol} = val; end"
end
end
class Person < Klass
add_getter_and_setter :name
add_getter_and_setter :phone
end
person = Person.new
person.name = 'John Smith'
person.phone = '555-2344'
person # returns <Person:0x28744 @name="John Smith", @phone="555-2344">
In the above example we created the class method with 'def self.add_getter_and_setter' but this is not the only way.
class Klass
class << self # opens the singleton class
def add_getter_and_setter(symbol) # note we dont specify self as it is already within the context of the singleton class
..
end
end
end
Using extend. Module#extend is a method that extends a class with class methods likewise the method Module#include includes a class with instance methods.
class Klass
extend(Module.new do
def add_getter_and_setter(symbol)
..
end
end)
end
If Klass has already been defined we can reopen it to add class methods
class Klass
end
def Klass.add_getter_and_setter(symbol)
..
end
# or
class << Klass
def add_getter_and_setter(symbol)
..
end
end
Well those are a few ways I know how to do this so if you see different syntax just realize its all doing the same thing.
Note: in rails a common class method we all use is 'find'. It is run directly off the Model class.
person = Person.find(1) # finds a person with id:1