Question

I want to include module MultipartForm to ApplicationController to extend some functionality for all controllers with methods from this module.

Every time I made a change in any controllers in app I got this error. So I have to restart my app. Then it's work fine.

From development.log

ActionController::RoutingError (uninitialized constant ApplicationController::MultipartForm):
  app/controllers/application_controller.rb:8:in `<class:ApplicationController>'
  app/controllers/application_controller.rb:3:in `<top (required)>'
  app/controllers/artists_controller.rb:1:in `<top (required)>'

My application_controller.rb is:

require_relative '../../lib/multipart_form'

class ApplicationController < ActionController::Base
  # Prevent CSRF attacks by raising an exception.
  # For APIs, you may want to use :null_session instead.
  #protect_from_forgery with: :exception

  include MultipartForm

  private

  def default_serializer_options
    {root: false}
  end

end

My multipart_form.rb is:

module MultipartForm
  # Use in controller like: send_multipart_form(:artist => artist_params)
  def send_multipart_form(send_params)
    _method = params && params[:_method] ? params[:_method].to_sym : :post
    RestClient.send _method, ActiveResource::Base.site.to_s + related_url, send_params
  end

  private

  def related_url
    _controller_path = params && params[:controller] ? params[:controller] : ""
    _id = params && params[:id] ? params[:id] : ""
    "#{_controller_path}/#{_id}"
  end
end

Can you suggest a solution how to extend controllers functionality with module and not need to restart server when any code changes. How to do it in best rails 4 way?

Some info:

Rails server => WEBrick 1.3.1
Rails version => 4.0.2
Env => development
Ruby version => ruby 2.0.0 (2013-11-22) [x86_64-linux]
Was it helpful?

Solution

The workaround is to use initializer. Create load_extensions.rb in rails initializers dir load_extensions.rb is:

ActiveSupport.on_load(:action_controller) do
  include MultipartForm
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top