jleeothon
jleeothon

Reputation: 3146

How to override the metaclass constructor in Ruby

I want a piece of code to run before any other static methods run, is it possible to do something in the spirit of the following?

class MyClass
  def self.initialize
    @stuff = 1
  end
  def self.print_stuff
    puts @stuff
  end
end

My Ruby version of interest is 2.3.

Upvotes: 0

Views: 122

Answers (2)

Max
Max

Reputation: 22325

Every chunk of code in Ruby is an expression. Even a class definition is a series of expressions: method definitions are expressions that have the side-effect of adding the method to the class.

This is how meta-programming methods work. attr_reader is a private method call where the implicit self is the class. So, long story short, you aren't restricted inside a class body, you can put whatever code you want to run in the context of the class:

class MyClass
  @stuff = 1

  def self.print_stuff
    puts @stuff
  end
end

Upvotes: 1

tadman
tadman

Reputation: 211560

There's no such thing as an explicit metaclass initializer. The class itself is "initialized" as it's defined, so it's perfectly valid to do this:

class MyClass
  # Code here will be executed as the class itself is defined.
  @stuff = 1

  def self.print_stuff
    puts @stuff
  end
end

MyClass.print_stuff

Remember that def itself is a form of method call and defining a class in Ruby involves sending a bunch of messages (method calls) around to the proper context objects, such as the class itself as it's being defined.

Upvotes: 0

Related Questions