pierrotlefou
pierrotlefou

Reputation: 40721

Automatically class level initialization in Ruby

In Java, we can conduct class level initialization in following way - that piece of code will be called automatically when class initialized. Can we achieve similar effect in Ruby?

static {
    initialization per class   
}

Upvotes: 4

Views: 188

Answers (2)

Daniel Rikowski
Daniel Rikowski

Reputation: 72504

Just add your code directly into the class body:

class MyClass

  @my_var = 'init1'
  my_method 'init2'

  def self.my_method(param)
  end

end

This code will be called when the class is loaded.

PS: If you are working on a Rails project you might be already familiar with that concept:

class MyModel < ActiveRecord::Base
  has_many
  belongs_to
  validates
  scope
end

All these methods are executed on the class level.

Upvotes: 1

Yossi
Yossi

Reputation: 12090

Ruby's classes are open which means that you can modify them in multiple places and in runtime. Therefore ruby has no class initialization.

However any code in inside your class definition will be executed:

class A
  def foo
  end

  print 'Declaring class A'
end

class A
  def bar
  end

  print 'Adding methods to class A'
end

Upvotes: 0

Related Questions