I am using a Rails engine as a gem in my app. The engine has PostsController
with a number of methods and I would like to extend the controller logic in my main
Here is what I put in my Rails 3 app in application.rb
after require 'rails/all'
(let me know if it is a bad place to put it)
require 'active_support/dependencies'
module ActiveSupport::Dependencies
alias_method :require_or_load_without_multiple, :require_or_load
def require_or_load(file_name, const_path = nil)
if file_name.starts_with?(Rails.root.to_s + '/app')
relative_name = file_name.gsub(Rails.root.to_s, '')
#@engine_paths ||= Rails::Application.railties.engines.collect{|engine| engine.config.root.to_s }
#EDIT: above line gives deprecation notice in Rails 3 (although it works in Rails 2), causing error in test env. Change to:
@engine_paths ||= YourAppName::Application.railties.engines.collect{|engine| engine.config.root.to_s }
@engine_paths.each do |path|
engine_file = File.join(path, relative_name)
require_or_load_without_multiple(engine_file, const_path) if File.file?(engine_file)
end
end
require_or_load_without_multiple(file_name, const_path)
end
end
For a while this didn't work raising
TypeError in PostsController#index
superclass mismatch for class PostsController
but that was due to a mistyped class definition class PostsController < ActionController::Base
which should be class PostsController < ApplicationController
If you do not want to do this for all engine controllers etc., you can load the engine's controller before the definition in the main app
require PostsEngine::Engine.config.root + 'app' + 'controllers' + 'posts_controller'
class PostsController < ApplicationController
# extended methods
end