Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails Engines: When to put code in app, when in lib, and when in vendor folder?

I'm developing a Rails engine, and so I've taken some looks on existing ones. I noticed that many of them have files in app, but also in lib and vendor.

It's clear to me that I should put any code that should be replaceable by the host app into the app folder (e.g. when having a model app/user.rb, the host app can easily have its own app/user.rb file and use this one instead of the engine one's).

But I'm unsure, when I have to put stuff in to lib, and when into vendor? I thought, that in vendor, I should only put "external" code from other developers or projects, that I want to use in my project, and in lib I put my own additional libraries that I'm actually working on in the project. But why, for example, does WiceGrid put stuff into its wice_grid/vendor/assets directory? It doesn't look to me like external code, but code that is developed only for WiceGrid and hence should be in the lib directory?

Update

While experimenting a bit, I noticed that all code in the lib folder is not reloaded while developing the engine (I guess the same is the case for the vendor directory), so I should put them into a folder within app, but where exactly?

For example, I have a file lib/iq_list_controller.rb that holds some class and instance methods for ApplicationController which I mix into it in engine.rb like this:

initializer "wice_grid_railtie.configure_rails_initialization" do |app|
  ActiveSupport.on_load(:action_controller) do
    extend  IqList::Controller::ClassMethods
    include IqList::Controller::InstanceMethods
  end
end

Where should I put this file so Ruby properly finds it?

like image 420
Joshua Muheim Avatar asked Oct 04 '12 09:10

Joshua Muheim


2 Answers

Regarding the development reloading issue, if the lib folder is a natural home for your files, then add it to Rails' load path with something like:

module MyEngine
  class Engine < ::Rails::Engine
    config.autoload_paths << File.expand_path("../../lib", __FILE__)
  end
end

Regarding the specific case of vendor assets, it seems reasonable to place your engine's assets in app/assets, where they will be found by the host Rails app.

like image 128
Andy Triggs Avatar answered Nov 07 '22 22:11

Andy Triggs


if you want things to be autoloaded then put them in /app. Otherwise I think that anything in /lib should be manually required. I generally believe that autoloading the lib folder is bad practice.

like image 44
Jason Waldrip Avatar answered Nov 07 '22 23:11

Jason Waldrip