Being Classy with HTTParty

I recently has a use for HTTParty in a project that potentially required multiple base_uri references at the same time. Just changing the base_uri isn’t thread-safe so you can’t do that so the most common way around this with HTTParty is to make an instance variable and pass that around to all of the calls to get/post/etc. I find that a little cumbersome so instead I made use of dynamic classes to hide all of that nonsense.

In a stripped down example, an HTTParty class looks somewhat like this:

class Foo
  include HTTParty
  base_uri 'http://example.com'

  def bar
    self.class.get '/some/resource'
  end
end

 

But rewriting it like so allows the same class usage but with variable base_uris:

class Foo
  class << self
    def new(uri, *args)
      Class.new(AbstractFoo) { |klass|
        klass.base_uri(uri)
      }.new(*args)
    end
  end

  class AbstractFoo
    include HTTParty

    def bar
      self.class.get '/some/resource'
    end
  end
end

foo1 = Foo.new('http://example.com')
foo2 = Foo.new('http://otherexample.com')

 

Thread-safe and no passing around stuff .. my little amusement for the day.

Bookmark and Share

About Kelley Reynolds

A full-stack software engineer, an avid trail runner, and a bassoonist. Kelley occasionally writes about one of his many projects on this blog.