Reputation: 553
I have to create a gazillion of ruby classes with similar structure, all of them look, lets say, like this:
class SomeName < SomeOtherName
def initialize
@title = "blablabla"
@link = "blablabla"
@nature = "blablabla"
end
end
Is it possible to store the classes in a form of datababase (SQL or Mongo, whatever). Something like this:
{:class => "SomeName", :parent => "SomeOtherName", :initialize => {"title
= "blablabla", ... } }
And be able to instantiate the classes from the database, of course. There should be literally hundreds of classes, storing them in ruby file would be too cumbersome, easy updating would be impossible. I was thinking about some alternatives, like creating one class to which you can send the data from database, so it can instantiate into different objects based on what you send into it, but inheritance is a big problem, also there likely to be methods other than initialize in some classes...
Upvotes: 1
Views: 523
Reputation: 10566
yes, you can.
It's Ruby meta-programming 101 via Class.new
Examples:
http://blog.rubybestpractices.com/posts/gregory/anonymous_class_hacks.html
http://blog.jayfields.com/2008/02/ruby-creating-anonymous-classes.html
For hacking in the names as you are retrieving them look at const_set like in this answer: Dynamically define named classes in Ruby
You would basically go over your db and just create the classes.
Upvotes: 1