开发者

Call method on included class in Ruby

开发者 https://www.devze.com 2022-12-28 07:11 出处:网络
How do you call the method of an included class in Ruby? See the example below. This works, but it is not what I want:

How do you call the method of an included class in Ruby? See the example below. This works, but it is not what I want:

require 'httparty'

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

    def initialize(path)
      # other code
    end

  end
end

This is what I want, but doesn't work, saying undefined method 'base_uri' [...]. What I'm trying to do is to set the base_uri of httparty dynamically from the initialize parameter.

require 'httparty'

module MyModule
  class MyClass
    include HTTParty

    def init开发者_运维百科ialize(path)
      base_uri 'http://localhost'
      # other code
    end

  end
end


According to the HTTParty source code, base_uri is a class method. So you would need to call the method on the class context

module MyModule
  class MyClass
    include HTTParty

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

  end
end

Beware that this solution might not be thread safe, depending on how you use your library.

0

精彩评论

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

关注公众号