Fun With Extend in IronRuby

Building on the implements idea from the last post, I’ve been playing around with extending CLR objects on the fly as I bring them at runtime. I wrote a quickie load_assemblies method that checks objects to see if they implement an interface, and extend them if they do.

I think this pattern will be very useful when importing existing .NET objects into IronRuby. For instance, if you wanted all of the objects governed by your ORM to take on ActiveRecord-like behavior, you could catch them and extend them like this:

class Class
  def implements? interface
    !to_clr_type.nil? && !to_clr_type.get_interface(interface).nil?
  end
end

def load_assemblies(assemblies)
  assemblies.each do |assembly| 
    require assembly
    System::Reflection::Assembly.load(assembly).get_types.each do |t|
      if t.to_class.implements? "IPersistence"
        t.to_class.extend ActsAsActiveRecord 
      end
    end
  end
  true
end

I’m sure there’s lots of other cool uses for the pattern… If anyone actually reads this shit and thinks of some, let me know. :)

This entry was posted on Mon, 30 Jun 2008 20:17:00 GMT and Posted in , . You can follow any any response to this entry through the Atom feed. You can leave a comments, .


Comments

Leave a response

Leave a comment