How to include module constants and variables?

I have a module with constant and variable.

I wonder how can I include them 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 it possible?

+5
source share
2 answers

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

This happens as you expect, but is @textset to Windowsnot 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
+3
source

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
+9
source

All Articles