Bastian
Bastian

Reputation: 207

How to autoload classes to use in controller

I have a class in libs and try to use it in a controller. However I cannot access it. I tried to use the autoload function, but that doesn't work, and it shouldn't work in rails 5 in production mode, so I guess I don't need to try this one.. I also tried to require it in my controller, but I don't get the syntax correct I guess. I'm also wondering where to put my class, since I have read several different opinions..

config/application.rb
 require_relative 'boot'

 require 'rails/all'

 # Require the gems listed in Gemfile, including any gems
 # you've limited to :test, :development, or :production.
 Bundler.require(*Rails.groups)

 module Qipmatedevel
   class Application < Rails::Application
     # Initialize configuration defaults for originally generated Rails version.
     config.load_defaults 5.1
     config.active_job.queue_adapter = :sidekiq
     config.autoload_paths += %W(#{config.root}/lib)
     # Settings in config/environments/* take precedence over those specified here.
     # Application configuration should go into files in config/initializers
     # -- all .rb files in that directory are automatically loaded.
   end
 end

app/controller/imports_controller
class ImportsController < ApplicationController

  require 'lib/class_qip'

Upvotes: 0

Views: 100

Answers (2)

Bastian
Bastian

Reputation: 207

adding

  require './lib/class_qip.rb'

fixed it

Upvotes: 1

ray
ray

Reputation: 5552

Put your classes in lib directory only & load as,

config.eager_load_paths << Rails.root.join('lib')

It works on both development and production environment.

Upvotes: 0

Related Questions