tags:

views:

108

answers:

4

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?

+5  A: 

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.

molf
Wow, nice ! thanks so much
marshluca
+4  A: 

This is probably better done using macros or scripts in your text editor. Creating classes programatically makes them hard to document.

Farrel
+1 for favoring code generation over runtime generation. The latter is sometimes the only way to do something, but it is usually not the best way.
OregonGhost
+3  A: 

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
severin
A: 

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.

Andrew Grimm