Today I was writing a library to access some API, in the design process I started wondering if in Ruby is possible to use some sort of namespacing on class.
All that I wanted was concatenating methods, like you do on active record objects. I show you the solution that I found:
module Test
module Foo
def bar
@namespace = "bar"
self
end
def bar_quack
puts "Quack!"
end
end
end
module Test
class Base
def initialize
puts "Init!"
end
def method_missing(method, *args)
if @namespace
self.send("#{@namespace}_#{method}", *args)
else
super
end
end
include Test::Foo
end
end
In this way you can do this:
test = Test::Base.new
#=> Init!
test.bar
#=>
test.bar_quack
#=> Quack!
test.bar.quack
#=> Quack!
The code works by implementing a method missing in the Base class, and a namespace method in the module that you want namespaced. All the method in the module must have the format: namespace_method.
Now when you call the namespace method an instance variable is set with the namespace, and self is returned.
Because the method cannot be found method missing is triggered, and is the instance variable is set we send the method with the namestace.
This is a quick way that I foud to achive a prettier way to access mehods. Bye!
Design by Simon Fletcher. Powered by Tumblr.
© Copyright 2010