How do the methods used within classes work?

Asked

Viewed 77 times

4

It is very common in Ruby to use methods within classes, such as attr_accessor, or even libraries, such as validates_presence_of, ruby on Rails.

I would like to create:

class Person
  add_name_getter "Luiz"
end

To add a field name class, with the value passed, as "Luiz", in the above example.

p = Person.new
p.name == "Luiz" # true

I know it’s a useless thing, but it’s just for example.

I tried to create a method like this:

def add_name_getter *args
  puts args.to_s
end

However, I did not receive any instance or class reference as a parameter.


Faced with this, remain the questions:

  • What they call these constructions?
  • What exactly are these constructions that are used in the classes (I referred to them as "methods", although I don’t know if they are exactly methods);
  • How can I create such a building?

1 answer

3


This kind of "building" is a method, but in some cases are also referred to as macros. So when do we:

class MyClass
  some_method()
end

The method some_method is being executed at the time when MyClass is evaluated. To understand this, it is necessary to know that, unlike languages like Java or C++, class is not only a definition, but an expression that is evaluated - and it is at this point that some_method is invoked. Adapted from another Stackoverflow response.

It is worth noting, still, that they are implicitly called with self, So, actually, what’s happening is this:

class MyClass
  self.some_method()
end

It means that some_method must be a class method, not an instance method. Thus, there are several ways to implement this some_method, such as:

In the class itself:

class MyClass
  def self.some_method
    puts "Hello, world!"
  end

  some_method
end

In a parent class, which will be inherited:

class Parent
  def self.some_method
    puts "Hello, world!"
  end
end

class MyClass < Parent
  some_method
end

With this, to implement the aforementioned add_name_getter, we can do it like this:

class UtilsClass
  def self.add_name_getter value
    # Criamos um método `:name` e retornamos `value` do método criado.
    define_method("name") do
      value
    end
  end
end

class MyClass < UtilsClass
  add_name_getter "Luiz"
end


ins = MyClass.new
p ins.name # => "Luiz"

I used the method define_method to add a method to MyClass dynamically.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.