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?
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With