3

I want to extend the models and controllers from Engine by reopening them in the Rails app. The problem is they are not loaded when the app starts. I know there are some solutions for this like Rails engines extending functionality and how to override rails 3 engine models and controllers in the main application?, but I suspect this is due to the loading sequence of rails, and there should be some neat solution.

Then I come across with this solution:

config.railties_order = [Blog::Engine, :main_app, :all]

However, models and controllers in Engine are loaded, but not the ones in rails. Just wondering if anyone made this work before?

Community
  • 1
  • 1
Tian Chen
  • 493
  • 4
  • 15
  • Here a clean solution [using concerns][1]. [1]: http://stackoverflow.com/questions/11675951/testing-model-extensions-for-engines – Andrea Reginato Jul 26 '12 at 18:43

2 Answers2

0

You can reopen the controller classes by having the main Rails application controllers inherit from a Rails Engine. This did not require the config.railties_order in order to get the controllers working,

#/app/controllers/answer_sheets_controller.rb
require YourCustomEngine::Engine.root.join('app', 'controllers', 'your_custom_engine', 'answer_sheets_controller')

class AnswerSheetsController < YourCustomEngine::AnswerSheetsController

From some reason, this strategy is not working for the models.

westonplatter
  • 1,475
  • 2
  • 19
  • 30
  • That's sad. But I have come up with another solution, see below. Not pretty but tidy (don't know how to put codes in the comments) – Tian Chen Jul 12 '12 at 12:00
  • @TinmanChan - here's another solution. https://groups.google.com/forum/?fromgroups#!topic/rubyonrails-core/jy2dQ0BQhnM – westonplatter Jul 13 '12 at 16:29
0

My Solution:

# === in engine
class EngineNameSpace::Blog
  # logic goes here
end

class Blog < EngineNameSpace::Blog
  # no codes should go here
end

# === in app
# If I need to extend the Blog class, I will code as below instead of reopenning the class
class Blog < EngineNameSpace::Blog
  # do something
end

Explain:

Rails blocks the engine classes from loading if they are the same file name/path as something in the parent app., see http://www.cowboycoded.com/2011/02/06/making-the-case-for-rails-3-engines/

Tian Chen
  • 493
  • 4
  • 15