Creating/accessing class vars from modules being used as mix


#1

Hello,
I’m writing a module that is to be used as a mixin for classes. I
cannot create or access class variables from within module methods.
Please look at this small pastie. It contains the module definitions,
class definitions, and some sample code that demonstrates the errors
I’m receiving.

http://pastie.caboo.se/39581

Thanks for the help,
– Christopher


#2

On Feb 11, 2007, at 4:26 PM, Christopher J. Bottaro wrote:

I’m writing a module that is to be used as a mixin for classes. I
cannot create or access class variables from within module methods.
Please look at this small pastie. It contains the module definitions,
class definitions, and some sample code that demonstrates the errors
I’m receiving.

Class variables have confusing inheritance rules, that I don’t think
are worth learning. (They are changing in a future version of Ruby.)

Instead, it’s almost always easier to use instance variables on the
class/module itself. Your code could do this with changes like:

module MyModule

def self.included base
   base.extend ForBase
end # def self.included

module ForBase

  def message
   @message
  end

  def message=(message)
   @message = message
  end

   def acts_as_whatever options = {}
      include MyModule::InstanceMethods
      extend MyModule::ClassMethods

      if options.has_key? :message
         self.message = options[:message]
      else
         self.message = "no message"
      end
   end # def acts_as_whatever

end # module ForBase

module InstanceMethods

   def show_message
      puts self.class.message
   end

end # module InstanceMethods

module ClassMethods

   def print_message
      puts message
   end

end # module ClassMethods

end # module MyModule

James Edward G. II


#3

Wow, thanks for the fast response. Your solution worked perfectly.
On a side note, this should definitely be in a FAQ somewhere (if it
isn’t already)… it’s kind of a hard problem to figure out if you
don’t know not to look at class variables.

Thanks again,
– Christopher

On Feb 11, 5:16 pm, James Edward G. II removed_email_address@domain.invalid