private include

T

trans. (T. Onoma)

Is there a simple way to include a module such that all the included methods
are private?

Thanks,
T.
 
S

Sam Stephenson

Is there a simple way to include a module such that all the included methods
are private?

If you can change the module definition itself, just add ``private''
before defining any methods.

If not, perhaps this would work:

| class Module
| def privately_include(mod)
| self.class_eval {include(mod)}
| mod.instance_methods.each do |m|
| self.class_eval {private m.to_sym}
| end
| nil
| end
| end

An example:

| irb(main):001:0> module Foo; def bar() end end
| => nil
| irb(main):002:0> class Baz; privately_include Foo end
| => nil
| irb(main):003:0> Baz.new.bar
| NoMethodError: private method `bar' called for #<Baz:0x402d4610>
| from (irb):3

Note that this won't make future public methods defined in the module
private in the including class.
Thanks,
T.

Sam
 
S

Sam Stephenson

If not, perhaps this would work:

Sorry, that was pretty ugly. Make that:

| class Module
| private
| def privately_include(mod)
| self.class_eval do
| include mod
| private *mod.instance_methods
| end
| end
| end

Sam
 
T

trans. (T. Onoma)

56:27 +0900, trans. (T. Onoma)
|
| > Is there a simple way to include a module such that all the included
| > methods are private?
|
| If you can change the module definition itself, just add ``private''
| before defining any methods.

Nope. It's FileUtils that I want to include.

| If not, perhaps this would work:
| | class Module
| | def privately_include(mod)
| | self.class_eval {include(mod)}
| | mod.instance_methods.each do |m|
| | self.class_eval {private m.to_sym}
| | end
| | nil
| | end
| | end
|

Thanks.

| Note that this won't make future public methods defined in the module
| private in the including class.

Right. Hmm... Module#method_added could do it.

T.
 

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

Staff online

Members online

Forum statistics

Threads
474,162
Messages
2,570,893
Members
47,432
Latest member
GTRNorbert

Latest Threads

Top