Running class from lib directory correctly

Hello

I’m getting these errors:

LoadError (Expected /home/amree/myapp/lib/company/api.rb to define Api):
  activesupport (3.2.13) lib/active_support/dependencies.rb:503:in `load_missing_constant'
  activesupport (3.2.13) lib/active_support/dependencies.rb:192:in `block in const_missing'
  activesupport (3.2.13) lib/active_support/dependencies.rb:190:in `each'
  activesupport (3.2.13) lib/active_support/dependencies.rb:190:in `const_missing'
  activesupport (3.2.13) lib/active_support/inflector/methods.rb:230:in `block in constantize'
  activesupport (3.2.13) lib/active_support/inflector/methods.rb:229:in `each'
  activesupport (3.2.13) lib/active_support/inflector/methods.rb:229:in `constantize'
  activesupport (3.2.13) lib/active_support/dependencies.rb:554:in `get'

I’m calling the class from this controller:

# myapp/app/controllers/api/something_controller.rb

class Api::SomethingController < ApplicationController
  def index
    # TODO: Verify q
    q = params[:q]

    @result = Company::Api.new().send("get_sdf_#{q}",
                                   rn: "123",
                                   limit: params[:limit])


  #...
end

And this is the class:

# myapp/lib/company/api.rb

module Company
  class Api
    include HTTParty

    base_uri "#{API_CONFIG['scheme']}://#{API_CONFIG['host']}"
    digest_auth API_CONFIG['email'], API_CONFIG['key']

    DEFAULT_OPTIONS = {
      limit: 1
    }

  #...
end

Thanks in advance.

@amree there probably some weirdness going on in the way the lib path is being loaded, how are you configuring the lib path to be autoloaded?

I’m using this setting:

# config/application.rb

config.autoload_paths += Dir["#{config.root}/lib/**/"]

Does it work if you explicitly include the company dir (i.e config.autoload_paths += Dir["#{config.root}/lib/company/"])?

I found a post on Stack Overflow that seems to indicate that this can be caused by a couple of different reasons: ruby on rails 3 - Inconsistent "LoadError" behavior with 'lib' namespacing/autoloading - Stack Overflow

1 Like

Seems like a right direction to my problem. I’ll get back once I’ve confirmed a few things. Thanks a lot

No problem, glad to help :slight_smile:

Hmm, using config.autoload_paths += Dir["#{config.root}/lib/company/"] will just throw error on other class in the lib.

However, using config.autoload_paths += Dir["#{config.root}/lib"] seems to be working just fine.