I don't understand the keywords like attr_reader
or property
in the following example:
class Voiture
attr_reader :name
attr_writer :name
property :id, Serial
property :name, String
property :completed_at, DateTime
end
How do they work? How can I create my own? Are they functions, methods?
class MyClass
mymagickstuff :hello
end
Those are class methods, you can add them to a class, or create your own class that has addition methods. In your own class:
Or to add to a class:
Once such a class method is defined, you can use it like this:
There are also ways to do this by adding modules to a class, which is often how rails does such things, such as using a
Concern
.You will want to monkey patch the class
Module
. That's where methods likeattr_reader
reside.As The Tin Man mentioned, monkey-patching base-level classes can be dangerous. Consider it like time-traveling into the past and adding something in the past. Just make sure that what you are adding isn't going to overwrite some other event or else you could come back to a Ruby script/timeline that isn't the same one you left.
That are just class methods. In this example
has_foo
adds afoo
method to an instance that puts a string: