在一个模块中,使用访问器会爆炸

时间:2015-10-04 15:44:54

标签: ruby

我的模块:

# test.rb
module Database
  # not used in this example, but illustrates how I intend to include the module in class
  def self.included(base)
    base.extend(ClassMethods)
  end
  module ClassMethods
    attr_accessor :db, :dbname
    self.dbname = ENV['RACK_ENV'] == 'test' ? 'mydb_test' : 'mydb'
  end
end

当我加载它时,我明白了:

test.rb:7:in `<module:ClassMethods>': undefined method `dbname=' for Database::ClassMethods:Module (NoMethodError)
    from bin/test:7:in `<module:Database>'
    from bin/test:1:in `<main>'

无法弄清楚原因。如果我检查instance_methods,它在attr_accessor之前为空,并且之后有相应的四种方法。然而,当我打电话给他们时,他们并不存在。

2 个答案:

答案 0 :(得分:1)

attr_accessor定义ClassMethods上的实例方法(例如ClassMethods#dbname=),但您尝试调用类方法(ClassMethods.dbname=)。

答案 1 :(得分:0)

使用 self.dbname = ENV ... ,您正在调用 #self.dbname = 的方法,该方法不存在。也许这就是你追求的目标?

# test.rb
module Database
  # not used in this example, but illustrates how I intend to include the module in class
  def self.included(base)
    base.extend(ClassMethods)
  end
  module ClassMethods
    attr_accessor :db, :dbname
    def self.dbname ; ENV['RACK_ENV'] == 'test' ? 'mydb_test' : 'mydb' ; end
    puts self.dbname
  end
end