How to define a class without a class statement in Ruby?

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

class A < ActiveRecord::Base
end

Is there a declaration statement to define a class without using an instruction class?

+3
source share
4 answers

If you know in advance which classes should be defined, you should probably generate code that explicitly defines them with a keyword classfor clarity.

However, if you really need to define them dynamically, you can use Object.const_setin conjunction with Class.new. To define a pair of child classes ActiveRecord::Base:

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

A..D, ActiveRecord::Base.

+6

, , . .

+5

You can define fully dynamic classes:

A = Class.new(ActiveRecord::Base) do
  # this block is evaluated in the new class' context, so you can:
  # - call class methods like #has_many
  # - define methods using #define_method
end
+3
source

I think Ruby Metaprogramming has a question on how to avoid using the keyword class, but I'm not sure if it will help you solve your problem.

0
source

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


All Articles