I have a module which I’m using to contain a lot of strings that my
objects print out. I want to use a module because it seems better to me
to put the data in a separate location than my object implementation, so
I can more easily see the logic of my object.
My object builds a set of text files. Each of these text files has
sections within them that are customised based upon a string handed in
to the object, such that:
bill = textFile.new(“bill”)
bill.header #returns “This is the header for bill”
bill.comment #returns “Bill is implemented with the following options:”
followed by the unique options for bill.
ted = textFile.new(“ted”)
ted.header #returns “This is the header for ted”
ted.comment #returns “ted is implemented with the following options:”
followed by the unique options for ted.
and so on.
Now, what I want is to have my Textfile class include a data module. The
data module contains all of the strings “This is the header for
#{variable}”, “#{variable} is implemented with the following options:”.
As such, I need to pass the argument to the textfile’s new method back
up into the module that the textfile includes.
I guess the question is, is there a way to reference a variable from a
class in a module that the class will include?
module M
> def self.m
> @x ||= 20
> end
> end
I do not think this is necessary
>
> class X
> include M
> def self.m
> anc = ancestors.find{ |a| a.respond_to?(:m) }
> anc.m if anc
replace this with instance_variable_get (potentially guarded by an
instance_variable_defined?)
I wonder however, what this is good for, I am not sure I understood
what OP wanted
HTH
R.
I thought modules sit further up the inheritance chain that classes?
This isn’t a case of inheriting down, this is a case of propagating back
up the chain.
It’s entirely possible I misunderstand, but Metaprogramming Ruby
definitely indicates that a module will sit above a class in an
inheritance chain.
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.