[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

module variables

OliverMarchand

5/23/2006 2:54:00 PM

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

2 Answers

Robert Klemme

5/23/2006 3:10:00 PM

0

OliverMarchand wrote:
> 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.

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

ts

5/23/2006 3:10:00 PM

0

>>>>> "O" == OliverMarchand <oliver.marchand@gmail.com> writes:

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


--

Guy Decoux