This post originated from an RSS feed registered with Ruby Buzz
by Daniel Berger.
Original Post: Making 'include' a little more flexible
Feed Title: Testing 1,2,3...
Feed URL: http://djberg96.livejournal.com/data/rss
Feed Description: A blog on Ruby and other stuff.
I've been following Ovid's journey into the trait forest with some interest. I brought up traits a while ago on the ruby-talk mailing list, and I've mentioned them in this journal from time to time.
The result is that I've been pondering how to cleanly implement these in Ruby without introducing new base types or syntax. I don't have an implementation, but I do have a theoretical syntax. Let's start with this example:
module TFoo
def method_a
"hello"
end
def method_b
"world"
end
end
module TBar
def method_a
"goodbye"
end
def method_b
"cruel world"
end
def method_y
"huh?"
end
end
With the current rules, if both of these modules are mixed into the same class then two of the methods, method_a and method_b are going to be overwritten, with nary a warning in site. Based on Curtis' Class::Trait syntax, I came up with the following:
class MyKlass
include TFoo,
:alias => {:method_a, :method_z},
:exclude => :method_b
include TBar
end
What would happen here? The methods of the TFoo module are mixed into MyKlass, except that "method_a" is defined as "method_z" within MyKlass. Note that this does not mean, as per the standard Ruby 'alias' method, that both "method_a" and "method_z" exist within MyKlass. Only "method_z" exists. In addition, the "method_b" method is specifically excluded, i.e. not mixed into MyKlass. Finally, the TBar module and all its methods are mixed in. Note that there is no conflict with "method_a" from TBar, since "method_a" from TFoo was aliased.
Mind you, this solution would require modifying "include" significantly, especially if we want to spew errors or warnings when method redefinition is detected. It also doesn't deal with nesting.
Considering how much traits focus on behavior, this may be a job for Sydney after all. :)