Austin Ziegler
2/19/2005 2:49:00 AM
On Sat, 19 Feb 2005 10:09:48 +0900, gga <GGarramuno@aol.com> wrote:
[...]
> 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
+ include B
+
> def afunc
> puts "afunc"
> bfunc
> end
> end
>
> ---- some other code
> require "A"
> class X
+ include A
+
> def initialize
> afunc # this should work
> bfunc # this should fail
> end
> end
I presume that you mean the include statements I placed above.
> 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.
This is not possible without doing some tricks. If you want A to
have access to B, but not allow X (which included A) to have access
to B, then you need to figure out some other way. Perhaps:
module B
def self.bfunc; end
end
module A
def afunc; B.bfunc end
end
class X
include A
def xfunc; afunc; end
end
But if A has included B, then when you include A, you'll get
everything that it knows about mixed into your class. This is the
fundamental capability of Ruby's mix-ins: the mix-in essentially
becomes a private part of the class into which it is mixed.
> 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.
try:
module Shell
def runcmd(command); ...; end
module_functtion :runcmd
end
class Backup
include Shell
end
It does the same thing as you did, except nicer.
-austin
--
Austin Ziegler * halostatue@gmail.com
* Alternate: austin@halostatue.ca