I heart Ruby: Metaprogramming

So today I had an interesting problem. For whatever the reason, I wanted to have a class automagically be created. It was going to be a helper model, and I didn't feel like having umteen classes that all did the same thing, just had different names for different tables. My solution: use the power of ruby and metaprogramming.

def create_new_active_record_model(class_name)
  klass = do
    belongs_to :old, :class_name => class_name
    def some_method_you_want
  Object.const_set "#{class_name}Target", klass

I know that some of this could have been encapsulated in a polymorphic association, but this allows you to do something beyond just keeping everything in one table, like with polymorphic associations.

This could be useful for creating something like a garbage collector. After something is deleted, it could go to this garbage heap. Having a lot of models would mean having a lot of garbage collection models. The garbage collection models could easily be abstracted enough so that one doesn't have to worry about the man behind the curtain.

In some ways it would be better than an acts_as_paranoid. For large tables there won't be data cluttering it up. Since all of the data is happening on live data, keeping the dirty out can help performance. Also, when I used acts_as_paranoid, I had to make sure that I put conditionals on all of my belongs_to and has_many statements; that way when I do something like user.posts, I wont get deleted posts.

If I had to compare it to something that already exists, it's like an acts_as_versioned, but it only cares when something is deleted.

When I get some more time, I will work on creating a acts_as_trashable or something of that nature :)


comments powered by Disqus