Hi all,
I have several classes in a module, thus:
module Example
class Ay
end
class Bee
end
end
I have a piece of data I want to share between classes Example::Ay and
Example::Bee, preferably without it being available to things outside the
module. What’s the best way to do this? As a class variable of Example
doesn’t seem to work, as I can’t access this from within Ay or Bee…
Tim Bates
···
–
tim@bates.id.au
Hi –
Hi all,
I have several classes in a module, thus:
module Example
class Ay
end
class Bee
end
end
I have a piece of data I want to share between classes Example::Ay and
Example::Bee, preferably without it being available to things outside the
module. What’s the best way to do this? As a class variable of Example
doesn’t seem to work, as I can’t access this from within Ay or Bee…
Here’s a start:
module Example
module Secret
class << self; attr_accessor :s; end
def s; Secret.s; end
def s=(n); Secret.s = n; end
end
class Ay
include Secret
end
class Bee
include Secret
end
end
Example::Ay.new.s = 10
p Example::Bee.new.s # => 10
You could also put a class variable in Secret and write accessor
wrappers for it (instead of an instance variable of Secret, which is
what I’ve done).
I don’t like repeating “Secret” in the method definitions; it feels
like there should be a more heuristic way to do that.
David
···
On Mon, 14 Apr 2003, Tim Bates wrote:
–
David Alan Black
home: dblack@superlink.net
work: blackdav@shu.edu
Web: http://pirate.shu.edu/~blackdav
Class variables are only available to a class and its descendants, so you
have to make both Ay and Bee inherit from a common ancestor:
module Example
module Shared
@@data = nil
end
class Ay
include Shared
def Ay.setit(x)
@@data = x
end
end
class Bee
include Shared
def Bee.putit
p @@data
end
end
end
Example::Ay.setit(42)
Example::Bee.putit #>> 42
Regards,
Brian.
···
On Mon, Apr 14, 2003 at 02:42:24PM +0900, Tim Bates wrote:
Hi all,
I have several classes in a module, thus:
module Example
class Ay
end
class Bee
end
end
I have a piece of data I want to share between classes Example::Ay and
Example::Bee, preferably without it being available to things outside the
module. What’s the best way to do this? As a class variable of Example
doesn’t seem to work, as I can’t access this from within Ay or Bee…