Search code examples
ruby-on-railsrubygoliath

Access Rails models inside a different module


I'm writing a web service for my Rails app using Goliath and I want to log all the requests sent to my web server. I have this Api class which is inside two modules:

require 'goliath'

module WebService
  module Rest
    class Api < Goliath::API
      def response(env)
        # Log the request
        Logger.create(id: params['id'], type: params['type'])

        [200, {}, "success"]
    end
  end
end

I have a model in app/models named Logger. The problem is when I run ruby api.rb -sv it throws an error:

uninitialized constant WebService::Rest::Api::Logger

What should I do? Thanks.


Solution

  • If you are running the Ruby code with ruby api.rb -sv and not via Rails itself (and, thus, the Rails environment is not loading and along with that, your models/ are not loaded).

    Run rails console from the Terminal (in your app directory) and then run your api code. You should be fine.