Include into class after instance is created

B

Brian Schroeder

Hello,

it's me again with another question. I want to include a module only after
having instantiated a class. Something like this

File: german.rb
Module Index
Title = 'Meine Seite'
end

File: english.rb
Module Index
Title = 'My Page'
end

file index.rb:
class Index < Website
def initialize
super
include(Index)
end
end

where Website requires either german.rb or english.rb.

But I can't call include as a function. Ruby complains that it is a
private function of class.

../index.rb:10:in `initialize': private method `include' called for Index:Class (NoMethodError)
from ./index.rb:27:in `new'
from ./index.rb:27

Is this scheme possible, am I totally on the wrong track or just missing
something obvious?

Regards,

Brian
 
B

Brian Schroeder

Use Object#extend instead of include.

Thanks for the tip.

I need the constants defined in the module to be included in my class, it
seems that extend only includes the instance methods.

$ ri extend
---------------------------------------------------------- Object#extend
obj.extend(module, ...) => obj
------------------------------------------------------------------------
Adds to _obj_ the instance methods from each module given as a
parameter.

Any thoughts about this?

Regards,

Brian
 
K

Kent S.

How about this:

$ irb
irb(main):001:0> module M1
irb(main):002:1> Const = 1
irb(main):003:1> end
=> 1
irb(main):004:0> module M2
irb(main):005:1> Const = 2
irb(main):006:1> end
=> 2
irb(main):007:0> class A
irb(main):008:1> def initialize(mod)
irb(main):009:2> self.class.class_eval{ include mod }
irb(main):010:2> end
irb(main):011:1>
irb(main):012:1*
irb(main):013:1* def const
irb(main):014:2> puts Const
irb(main):015:2> end
irb(main):016:1> end
=> nil
irb(main):017:0> A.new(M1).const
1
=> nil
irb(main):018:0> A.new(M2).const
2
=> nil
irb(main):019:0>


Cheers,
Kent.
 

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,776
Messages
2,569,603
Members
45,189
Latest member
CryptoTaxSoftware

Latest Threads

Top