在Ruby中包含类的调用方法

你如何在 Ruby中调用包含类的方法?请参阅下面的示例.这有效,但它不是我想要的:

require 'httparty'

module MyModule
  class MyClass
    include HTTParty
    base_uri 'http://localhost'        

    def initialize(path)
      # other code
    end

  end
end

这就是我想要的,但不起作用,说未定义的方法’base_uri'[…].我要做的是从initialize参数动态设置httparty的base_uri.

require 'httparty'

module MyModule
  class MyClass
    include HTTParty

    def initialize(path)
      base_uri 'http://localhost'
      # other code
    end

  end
end

解决方法

根据 HTTParty source code,base_uri是一种类方法.
所以你需要在类上下文中调用该方法

module MyModule
  class MyClass
    include HTTParty

    def initialize(path)
      self.class.base_uri 'http://localhost'
      # other code
    end

  end
end

请注意,此解决方案可能不是线程安全的,具体取决于您使用库的方式.

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...