[Ironruby-core] A nicer syntax for generic extension methods

Ryan Riley ryan.riley at panesofglass.org
Mon Feb 1 13:52:13 EST 2010

I have been trying to figure out how to Rubify generic extension methods for
use with the likes of Rx, Open XML SDK, etc. Ivan went over it a bit with me
this weekend, but I'm still having difficulty including a module within a
.NET type. Is that even possible?

names = System::Collections::Generic::List.of(System::String).new
names.add 'Ryan'

Current syntax:
greetings = System::Linq::Enumerable.method(:select).of(System::String).call
{ |name| "Howdy, #{name}" }
# compare with greetings = names.map { |name| "Howdy, #{name}" }

Desired syntax:
greetings = names.linq_select { |name| "Howdy, #{name}" }

Granted, you might make a case for using the Ruby Enumerable methods over
Linq, but when it comes to using other libraries, the more Ruby-like syntax
would be preferred. In the interest of working out the preferred syntax, I
thought using System.Linq.Enumerable would be easiest.

Ivan provided the following:

module EnumerableExtensions

 def included(base)
 if base.respond_to? :to_clr_type
 @klass = base.to_clr_type

def linq_select(&b)
 System::Linq::Enumerable.method(:select).of(@klass).call &b


The questions I'm not able to answer are:

   1. Can I somehow open up a .NET class, say
   System::Collections::Generic::List[T] and include the EnumerableExtensions?
   So far, I'm finding that's a no.
   2. How do I hook in the included(base) method above? I'm assuming that's
   a one-time call, but I don't see anywhere that it's called when a module is
   included. Do I need to use a before_filter or perform that action at the
   beginning of the linq_select method?


Ryan Riley

Email: ryan.riley at panesofglass.org
LinkedIn: http://www.linkedin.com/in/ryanriley
Blog: http://wizardsofsmart.net/
Twitter: @panesofglass
Website: http://panesofglass.org/
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://rubyforge.org/pipermail/ironruby-core/attachments/20100201/330e36a5/attachment.html>

More information about the Ironruby-core mailing list