ruby-on-railscode-organizationproject-organization

What's the best place to put all logic about generating a report in ruby on rails?


I have many models which I use to obtain data and generate a report.

The report doesn't need to be stored, i.e. it's not an active record.

But certainly there's like 80 lines of code which generate the data for the report.

Where should I put those lines?

They are currently in the controller but since controller should be thin, I'm not sure if that's the best place.


Solution

  • I would create a directory in app called reports, and put all of my reports in there.

    Everything in the app directory in rails can be found as long as the filename and class follow the normal convention.

    For example, if you have the following in app/reports/example_report.rb:

    class ExampleReport
      def initialize
        ...
      end
    end
    

    You will be able to use it from your controllers as such:

    class SomethingController < ApplicationController
      def something
        example = ExampleReport.new
        ...
      end
    end
    

    Reports that rely on models are considered part of your application's domain, which is why I recommend the app directory. The ease of adding subdirectories in app means that you can maintain a logical separation of the different roles in your application. It shouldn't be hard to guess where the implementation for something is. Controllers are in app/controllers, models are in app/models, so it follows that reports are in app/reports. And for example, if you were to add generic service classes to your app, they could go in app/services.

    In contrast, they do not belong in lib, because they cannot function in a generic fashion. To further this point, only code that you could envision being used in any rails project belongs in the lib directory.