-1

I'm building a platform in Rails that will act as a basis for a few other Rails applications. Ideally I would like this to be a shared engine, on which the other concrete applications can build.

It would be nice if the applications could extend the base classes that the engine provides. AFAIK this can be done using monkey patching, but that feels 'hacky' to me.

I stumbled onto what looked like the solution, which was to just create 'mirror' classes in the main Rails app, which extend those of the engine:

# SharedEngine/models/shared_engine/post.rb
module SharedEngine
  class Post < ActiveRecord::Base
    def hello
      "Hello"
    end
  end
end

# App/models/shared_engine/post.rb
require SharedEngine::Engine.root.join('app', 'models', 'shared_engine', 'post')

class Post < SharedEngine::Post
  def hello
    super + " world"
  end
end

However, it looks like there are some autoloading problems. After server startup, it prints "Hello". Then after I save the app model, it says "Hello world".

The Rails engine guide suggests putting shared code into concerns. Is there any other way to get this working cleanly without having to create concerns for every class?

Rengers
  • 14,911
  • 1
  • 36
  • 54
  • Class reloading will only occur on a development environment and most autoloading issues can be bypassed using: [Rails::Railtie::Configurartion#to_prepare](http://api.rubyonrails.org/classes/ActionDispatch/Reloader.html#method-c-to_prepare). Although this is not the suggested way to deal with it. See my answer below. – Dimitris Zorbas Jun 20 '15 at 11:57

1 Answers1

0

Since you need to create a basis for a few Rails apps to reduce boilerplate i suggest having a look a Rails Application Templates. Using templates you may provide all the necessary scaffolding without monkey-patching any class.

Dimitris Zorbas
  • 5,187
  • 3
  • 27
  • 33