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?
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
.
This is probably better done using macros or scripts in your text editor. Creating classes programatically makes them hard to document.
You can define classes completely dynamic:
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
I think "Metaprogramming ruby" has a quiz question on how to avoid using the class
keyword, but I'm not sure if that's going to help you fix your problem.