module variables

O

OliverMarchand

Dear Ruby people,

I understand that modules are used for mixins and namespace management.
Now I am confused about module variables. Here is a sample problem:

---------
module MyMod

attr :myvar, true

def MyMod.othervar=(val)
@othervar = val
end

end

MyMod.myvar = 1 ### this doesn't work
### "undefined method `myvar=' for
MyMod:Module (NoMethodError)"
MyMod.othervar = 1 ### this does!

### I know this works, but is not what I want...

class Klass
include MyMod
end

klass = Klass.new
klass.myvar = 1
---------

So it seems to me that the "attr" call does not create the accessor
functions until an object is instanciated. But what do I do if I want
to solely bundle some functions in a module for namespace management
and store some data that is associated with that module? Do I have to
explicitly write the accessors?

cheers,
Oliver
 
R

Robert Klemme

OliverMarchand said:
Dear Ruby people,

I understand that modules are used for mixins and namespace management.
Now I am confused about module variables. Here is a sample problem:

---------
module MyMod

attr :myvar, true

def MyMod.othervar=(val)
@othervar = val
end

end

MyMod.myvar = 1 ### this doesn't work
### "undefined method `myvar=' for
MyMod:Module (NoMethodError)"
MyMod.othervar = 1 ### this does!

### I know this works, but is not what I want...

class Klass
include MyMod
end

klass = Klass.new
klass.myvar = 1

Not exactly. The accessor is there but it's an instance method (i.e.
instances of the class can use it) vs. a singleton method of the module.
You've mixed these two things.
But what do I do if I want
to solely bundle some functions in a module for namespace management
and store some data that is associated with that module? Do I have to
explicitly write the accessors?

You can do this:

module Mod
class <<self
attr_accessor :myvar

def do_something(x)
x + myvar
end
end
end

Mod.myvar = 10
Mod.do_something 20 # -> 30


Kind regards

robert
 
T

ts

O> module MyMod

O> attr :myvar, true

You have denied an instance variable, when you want a class instance
variable, try it with

class << self
attr :myvar, true
end

O> def MyMod.othervar=(val)
O> @othervar = val
O> end

O> end
 

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
474,169
Messages
2,570,919
Members
47,459
Latest member
Vida00R129

Latest Threads

Top