Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails Engines: Helpers only are reloaded when restarting the server

I'm currently experimenting with moving functionality into engines. It works nicely so far, but I'm a bit confused why certain parts of the engine are always automatically reloaded when something changed, and some are not.

Specifically, when adding a helper method, I have to restart the Rails server, otherwise it is not seen by Rails. Is this normal behavior? Here's the relevant part of my engine:

components/iq_list.rb

# encoding: utf-8
require 'iq_list/engine'

# Load IqList Modules
module IqList
  extend ActiveSupport::Autoload
  autoload :Helpers
  autoload :Models
  autoload :Controllers
end

components/iq_list/engine.rb

module IqList
  class Engine < ::Rails::Engine
  end
end

components/iq_list/helpers.rb

module IqList
  module Helpers
    extend ActiveSupport::Autoload
    autoload :IqListHelper
  end
end

components/iq_list/helpers/iq_list_helper.rb

module IqList
  module Helpers
    module IqListHelper
      def some_method
        # ...
      end
    end
  end
end

I'm still very new to engines, and a lot of the code above I have taken from somebody else's work, so please be patient with me. Any hint into the right direction is highly appreciated.

like image 674
Joshua Muheim Avatar asked Aug 30 '12 07:08

Joshua Muheim


2 Answers

It appears that you may be barking up the wrong tree with Engines. If you're trying to simply achieve separation of concerns, you probably just want to make some plain old ruby classes and stick them in lib/ (in an organized way of course).

An Engine would be developed separately from your 'current' project at likely brought in through a gem. Changes in included gems would necessitate restarting your server AFAIK.

like image 80
Robert Pitts Avatar answered Nov 15 '22 21:11

Robert Pitts


If you need code from your engine reloaded on every request you need to place it in the to_prepare block of the engines intialization code

module IqList
  class Engine < ::Rails::Engine
    config.to_prepare do
     ApplicationController.helper(IqListHelper)
    end
  end
end

Code in the to_prepare block is guaranteed to run once in production and every time in development.

see the rails guides as well as What does this Rails Engine code mean: config.to_prepare &method(:activate).to_proc

and

http://robots.thoughtbot.com/tips-for-writing-your-own-rails-engine

like image 21
hraynaud Avatar answered Nov 15 '22 23:11

hraynaud