marshluca
marshluca

Reputation: 931

how to define a class without 'class' statement in 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?

Upvotes: 4

Views: 321

Answers (4)

Andrew Grimm
Andrew Grimm

Reputation: 81691

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.

Upvotes: 0

severin
severin

Reputation: 10268

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

Upvotes: 3

molf
molf

Reputation: 75035

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.

Upvotes: 7

Farrel
Farrel

Reputation: 2381

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

Upvotes: 5

Related Questions