Call method on included class in Ruby
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.
精彩评论