Automatic class level initialization in Ruby

In Java, we can initialize the class level as follows: this piece of code will be called automatically when the class is initialized. Can we achieve a similar effect in Ruby?

static { initialization per class } 
+4
source share
2 answers

Just add your code directly to 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 may already be familiar with this concept:

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

All of these methods are executed at the class level.

+1
source

Ruby classes are open, which means you can modify them in different places and at runtime. Therefore, ruby ​​does not have class initialization.

However, any code inside your class definition will execute:

 class A def foo end print 'Declaring class A' end class A def bar end print 'Adding methods to class A' end 
0
source

Source: https://habr.com/ru/post/1482795/


All Articles