How to Dynamically Create ActiveRecord Classes
A question came up on IRC on someone commenting on how it was a pain to have a file for each ActiveRecord class if they were all really simple and basically the same. I cooked up the following code for him.
def create_activerecord_class table_name
Class.new(ActiveRecord::Base) do
set_table_name table_name
end
end
# I already have a users db table
# So in the console...
>> AnotherUser = create_activerecord_class(:users)
=> AnotherUser(id: integer, first_name: string, last_name: string, ...... )
>> AnotherUser.count
=> 29605
So, in your environment file (or some other appropriate place), you can create these classes with just one line of code per class. Of course, the method that creates the class can get more complicated - you could pass in options if the classes needed to differ from each other. This is a really simple example of the power of metaprogramming - writing code that writes code.
Quite helpful if you don’t want to repeat yourself all the time.