Pages

Tuesday, June 21, 2011

Ruby Modules: A perfect name space resolver?

Coming from java background, I was looking for package equivalent in Ruby and read in Programming Ruby 1.9 book that Ruby Module serves two purposes, 1) Namespace conflict resolver 2) Mixin Though, mixin is applauded one, now the one that bothers me is Namespace conflict resolver. lemme idealize it in to a simple example
module A

def test
  puts "I am in module A"
end

end

module B

def test
  puts "I am in module B"
end

end

Class Payment

include A
include B

end

p = Payment.new

p.test #prints - I am in module A

Now how to invoke test method in module B? But the same if I rewrite the those module methods as a class level methods, this works
module A

def self.test
  puts "I am in module A"
end

end

module B

def self.test
  puts "I am in module B"
end

end

Class Payment

include A
include B

def test_modules
  A.test
  B.test
end

end

p = Payment.new

p.test_modules #prints fine - I am in module A, I am in module B

when I do,
p.A.test #bangs - `
': undefined method `A' for # (NoMethodError)
What is this actually? I couldn't understand the concept, Is someone who could help me on this? Is Ruby a perfect namespace conflict resolver?

P.S - I got to know clear about this by watching this video MetaProgramming for Fun by Dave Thomas

2 comments:

Juice10 said...

Wouldn't it be better to ask this question on stack overflow?

Anonymous said...

The manufacturing method was created by Aimé-Gabriel d’Artigues. Since then, the company has continued its seek for pleasure by providing its savoir-faire to passionate connoisseurs. NetEnt is dedicated to gaming that is fun, protected, and safe. This is when the Banker holds a higher card value and is asserted the winner. A tie is calculated when both the Player and the 카지노사이트 Banker have the precise complete quantity.