Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to define a class without 'class' statement in Ruby?

Tags:

class

ruby

I have many classes to define, but I don't want to repeat the below work:

class A < ActiveRecord::Base
end

Is there any declaration statement to define a class without using the class statement?

like image 534
marshluca Avatar asked Dec 08 '22 04:12

marshluca


1 Answers

If you know in advance exactly which classes need to be defined, you should probably generate code that explicitly defines them with the class keyword for clarity.

However, if you really need to define them dynamically, you can use Object.const_set in combination with Class.new. To define a couple of child classes of ActiveRecord::Base:

%w{A B C D}.each do |name|
  Object.const_set name, Class.new(ActiveRecord::Base)
end

The result of the above is four new classes named A..D, all children of ActiveRecord::Base.

like image 190
molf Avatar answered Dec 28 '22 21:12

molf