"is it thread safe to set active resource http authentication on a per-user basis?" Code Answer

3

monkey patch the host, user and password methods of activeresource::base class:

class activeresource::base
  # store the attribute value in a thread local variable
  class << self
    %w(host user password).each do |attr|               

      define_method(attr) do
        thread.current["active_resource.#{attr}"]
      end

      define_method("#{attr}=") do |val|
        thread.current["active_resource.#{attr}"] = val
      end
    end
  end
end

now set the credentials in every request

class applicationcontroller < actioncontroller::base

  around_filter :set_api_credentials

private 

  # set the credentials in every request
  def set_api_credentials
    activeresource::base.host, 
      activeresource::base.user, 
        activeresource::base.password = current_user_credentials
    yield
  ensure
    activeresource::base.host = 
      activeresource::base.user = 
        activeresource::base.password = nil
  end

  default_host, default_user, default_password= [
    "http://www.foo.com", "user1", "user78102" ]

  def current_user_credentials
    current_user.present? ? 
      [ current_user.host, current_user.login, current_user.password] : 
      [ default_host, default_user, default_password]
  end

end
By sxclegz on August 15 2022

Answers related to “is it thread safe to set active resource http authentication on a per-user basis?”

Only authorized users can answer the Search term. Please sign in first, or register a free account.