Having made the commitment to ruby, I am now finding myself building
bigger frameworks and ruby's limited namespace rules with modules are
potentially showing some issues that I want to either prepare for or
avoid.
Or perhaps it is not entirely clear to me what's the proper Ruby way of
doing it. Basically I am building some libraries and I am trying to be
careful about name pollution.
I have a bunch of functions that, currently, have no particular class
location. Currently, I am placing them in modules.
As I have a bunch of them that are somewhat unrelated, I have been
creating modules following the standard procedure I've used in other
languages. That is, I'm using:
module MyCompany
module Module
def self.func1
end
def func2
end
end
end
Now... the problems I am facing are...
1) Ruby's name pollution on includes.
--- B ---
module B
def bfunc
puts "bfunc"
end
end
--- A ---
require 'B'
module A
def afunc
puts "afunc"
bfunc
end
end
---- some other code
require "A"
class X
def initialize
afunc # this should work
bfunc # this should fail
end
end
···
===============================
I want to have code that includes A, but does not include B. However,
class X should not have access to functions in module B, which it never
included.
How can I safely work around this? I want to avoid behaviors or
anything like that.
2) I also would like to have some modules that work either as include
modules or as modules with stand-alone methods. Problem is that ruby
will not "include" class methods.
That is, say I have a funcion called runcmd() to run a shell command
and do stdin/out/err piping. This function is rather common, so I
would like to have:
module Shell
def self.runcmd(cmd)
# ....do tons of stuff
end
def runcmd(cmd)
Shell.runcmd(cmd)
end
end
So I can do:
Shell.runcmd("ls")
or:
class Backup
include Shell
def doit
runcmd("ls")
runcmd("cmd2")
end
....etc..
end
The above works but it seems kind of silly and wasteful for something
that to me seems pretty common (not to mention that the instance method
access will likely be slower, too).