Forum: Ruby creating/accessing class vars from modules being used as mix

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Christopher J. Bottaro (Guest)
on 2007-02-12 00:26
(Received via mailing list)
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
James G. (Guest)
on 2007-02-12 01:16
(Received via mailing list)
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
Christopher J. Bottaro (Guest)
on 2007-02-12 01:28
(Received via mailing list)
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>
This topic is locked and can not be replied to.