开发者

Class variables and extending a module

开发者 https://www.devze.com 2023-01-22 19:55 出处:网络
I have a module like the following module MyModule def self.included(base) base.extend ClassMethods end module ClassMethods

I have a module like the following

module MyModule
  def self.included(base)
    base.extend ClassMethods
  end

  module ClassMethods
    def foo
      @@var = 1
    end

    def bar
      puts @@var
    end
  end
end

class A
  include MyModule
  foo
end

class B < A; end

so that

 B.bar outputs '1'.

However, I would like to have .bar only be de开发者_运维问答fined if .foo is called. I tried

module MyModule
  def self.included(base)
    base.extend ClassMethods
  end

  module ClassMethods
    def foo
      @@var = 1
      extend SingletonMethods
    end

  module SingletonMethods
    def bar
      puts @@var
    end
  end
end

The problem is that

B.bar

returns the error "uninitialized class variable @@var in MyModule::SingletonMethods". How can I make it so that a variable defined in .foo is available to .bar?


use mattr_accessor instead


I was able to access class variables from a module using the self syntax

class User
  include Base
  @@attributes = [:slug, :email, :crypted_password]
end

module Base
  def self.included(base)
  base.extend ClassMethods
end

def headers
  if defined? self.attributes
    self.attributes
  end
 end
end

Now calling User.headers gives me the expected result of [:slug, :email, :crypted_password]

If anyone can shed more light on why this works exactly so in ruby, please let me know!

0

精彩评论

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