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
endI’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. :)