Mark
Mark

Reputation: 10988

How to require modules in Rails

I have rails app with a module called http_helpers that lives in app/lib/modules/ and I want to use the methods in the module in my controllers. I was thinking of requiring the module in application_controller.rb so that the module's methods will be accessible to every controller.

application_controller.rb

class ApplicationController < ActionController::Base
  protect_from_forgery with: :exception
  require "http_helpers"
end

However I'm getting an error:

LoadError (cannot load such file -- http_helpers):

I'm new to dealing with this side of rails (or ruby for that matter) and would very much appreciate some suggestions.

Thanks in advance!

Upvotes: 3

Views: 7122

Answers (2)

Richard Peck
Richard Peck

Reputation: 76774

If you're using Rails 5+ (you have not specified), you can now include helpers directly in the controller using the helpers method:

class ApplicationController < ActionController::Base
  def index
    helpers.your_http_method
  end
end

If your module has specific helpers, you should convert it into an engine and then put the helpers into the app/helpers folder of your engine. We do this with a framework we use in our production apps:

enter image description here

This will allow you to call the helpers in your controllers without polluting your app's structure.

--

The trick is to make the engine a gem and put it in vendor/gems - this way you can reference it in the Gemfile as follows:

#Gemfile
gem "your_engine", path: "vendor/gems/your_gem"

If you decide to extract the functionality into an engine (you should), the setup would be as follows:

# app/vendor/gems/your_engine/lib/engine.rb
module YourEngine
  class Engine < Rails::Engine
    isolate_namespace YourEngine
  end
end

# app/vendor/gems/your_engine/app/helpers/your_engine/http_helpers.rb
class YourEngine::HTTPHelpers
  ....
end

Upvotes: 1

Andrey Deineko
Andrey Deineko

Reputation: 52347

You use Module#include/extend modules, not files in Rails, because every file (at least those under app directory are preloaded).

So

class ApplicationController < ActionController::Base
  include HttpHelpers
  protect_from_forgery with: :exception
end

edit

Unless you're on Rails 5+, you need to add the folder to the autoload paths:

#config/application.rb:
config.autoload_paths << Rails.root.join('app', 'lib', 'modules')

Upvotes: 2

Related Questions