Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the nature of "property" in a Ruby class?

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
like image 280
DrIDK Avatar asked Sep 27 '13 16:09

DrIDK


People also ask

What is property in Ruby Rails?

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.

How do classes work in Ruby?

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.

What does Attr_reader do in Ruby?

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.

What is Attr_accessor in Ruby?

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.


1 Answers

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
like image 63
spickermann Avatar answered Nov 15 '22 04:11

spickermann