← Back to Upcase

Running class from lib directory correctly


(Amree Zaid) #1

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.


(Pedro Moreira) #2

@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?


(Amree Zaid) #3

I’m using this setting:

# config/application.rb

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

(Pedro Moreira) #4

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: http://stackoverflow.com/questions/7081782/inconsistent-loaderror-behavior-with-lib-namespacing-autoloading


(Amree Zaid) #5

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


(Pedro Moreira) #6

No problem, glad to help :slight_smile:


(Amree Zaid) #7

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.