开发者

How to include a Module's constants and variables?

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"
   开发者_StackOverflow puts @text
  end
end

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

Windows.start

Is this possible?


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


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜