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
property is called when the class definition is executed, which means it can add methods to the class. With this, we can define a method, which will then be part of the class. Add this code to the property function: define_method(sym) do. instance_variable_get("@#{sym}") end.
In Ruby, a class is an object that defines a blueprint to create other objects. Classes define which methods are available on any instance of that class. Defining a method inside a class creates an instance method on that class. Any future instance of that class will have that method available.
Summary. attr_reader and attr_writer in Ruby allow us to access and modify instance variables using the . notation by creating getter and setter methods automatically. These methods allow us to access instance variables from outside the scope of the class definition.
attr_accessor is a shortcut method when you need both attr_reader and attr_writer . Since both reading and writing data are common, the idiomatic method attr_accessor is quite useful.
That are just class methods. In this example has_foo
adds a foo
method to an instance that puts a string:
module Foo
def has_foo(value)
class_eval <<-END_OF_RUBY, __FILE__, __LINE__ + 1
def foo
puts "#{value}"
end
END_OF_RUBY
end
end
class Baz
extend Foo
has_foo 'Hello World'
end
Baz.new.foo # => Hello World
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