Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to include a Module's constants and variables?

Tags:

ruby

I have a Module with a constant and variable.

I wonder how I could include these in a class?

module Software
  VAR = 'hejsan'

  def exit
    @text = "exited"
    puts @text
  end
end

class Windows
  extend Software
  def self.start
    exit
    puts VAR
    puts @text
  end
end

Windows.start

Is this possible?

like image 226
never_had_a_name Avatar asked Jul 29 '10 00:07

never_had_a_name


2 Answers

Ruby 1.9.3:

module Software
  VAR = 'hejsan'

  module ClassMethods
    def exit
      @text = "exited"
      puts @text
    end
  end

  module InstanceMethods

  end

  def self.included(receiver)
    receiver.extend         ClassMethods
    receiver.send :include, InstanceMethods
  end
end

class Windows
  include Software
  def self.start
    exit
    puts VAR
    puts @text
  end
end

Windows.start

In IRB:

exited
hejsan
exited
like image 185
kwerle Avatar answered Sep 22 '22 08:09

kwerle


Doing exactly what you want is not possible. Instance variables are strictly per object.

This happens to do what you expect, but @text is set on Windows not Software.

module Software
  VAR = 'hejsan'

  def exit
    @text = "exited"
    puts @text
  end
end

class Windows
  class <<self
    include Software
    def start
      exit
      puts VAR
      puts @text
    end
  end
end

Windows.start
like image 34
taw Avatar answered Sep 23 '22 08:09

taw