Accessing functions in a module without 'include'

R

Ronald Fischer

Usually I work with modules like this:

# Defining a module in one file
module M
def f(x)
....
end
end

# Using the module in another file
require 'M'
include M
f(45)

Sometimes I would find it more convenient to *not* inject
the module's namespace into the user's namespace, i.e. to
do it without the include statement. I thought it would=20
be easy to qualify the foreign function with the module
name:

# Using the module in another file
# (this does not work)
require 'M'
M::f(45) # Error: undefined method 'f'

Maybe I'm thinking to Perlish here. Can it be done what I want
to achieve, and how?

Ronald
--=20
Ronald Fischer <[email protected]>
Phone: +49-89-452133-162
=20
 
R

Ronald Fischer

Sometimes I would find it more convenient to *not* inject
=20
Not sure if it's what you want, but if you define M as=20
follows it works:
=20
module M
def self.f(x)
....
end
end

Thank you, this works perfectly well!

Ronald
 
R

Ronald Fischer

# Defining a module in one file
module M
module_function # <<<<<<<<< HERE
def f(x)
....
end
end

Thank you, this is indeed one solution to my problem (though in the
end, I'm going to stick with Michael Hollins' proposal).

Ronald
 
T

Trans

Thank you, this is indeed one solution to my problem (though in the
end, I'm going to stick with Michael Hollins' proposal).

Don't mention it :) BTW, Just to make sure you know, you can't use
Micheal's solution if you still want the option of including the
Module elsewhere. In effect using module_function is the same as:

module M
def self.f(x)
....
end
def f(x)
....
end
private :f
end

Probably you've already figured that out, but just in case...

T.
 
R

Ronald Fischer

BTW, Just to make sure you know, you can't use
Micheal's solution if you still want the option of including the
Module elsewhere. In effect using module_function is the same as:
=20
module M
def self.f(x)
....
end
def f(x)
....
end
private :f
end

I wasn't aware that the instance functions would then go private,
but in my case this would be no problem anyway.

Ronald
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,764
Messages
2,569,566
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top