Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call method on included class in Ruby

Tags:

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 initialize(path)
      base_uri 'http://localhost'
      # other code
    end

  end
end
like image 809
Mads Mobæk Avatar asked Apr 22 '10 13:04

Mads Mobæk


1 Answers

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.

like image 131
Simone Carletti Avatar answered Sep 27 '22 22:09

Simone Carletti