0

Saying I am writing an action in my controller.

While it has many logics: several if statements, also has cases.

Is there a way that I can group these logics, for instance, I want all the if statements to be in one file and case statements in another file. so in my controller, I do not have to write whole bunch of codes, I can just call the files that contain these statements. Like in HTML we use script tag to include JS files

And maybe other action can also use these files in the future.

lilixiaocc
  • 313
  • 1
  • 11

2 Answers2

1

Your controller's actions shouldn't contain that volume of business logic. There are many potential solutions:

  • You can move your logic into your model layer, using model concerns to share logic amongst models

  • Distill your action's logic into several reusable methods, and move those methods into your ApplicationController so that they can be reused by any controllers that inherit from your ApplicationController.

  • Introduce a controller concern, containing the relevant logic chunked into methods, and include that concern in the controllers that need access to the logic.

Moving slightly away from the built-in Rails conventions, you can introduce a layer of "service" objects that you can instantiate to hold reusable blobs of business logic that don't necessarily fit into your model layer.

These are often called "services" or "operations", and reside in app/services and app/operations respectively. In terms of code structure, these would be simple classes that accept inputs from your controller, perform complex operations on your model layer, and then make output available to your controller so that it can be rendered to the user.

There is an additional set of Rails conventions defined in a project called TrailBlazer that might be a useful template on which to model your own service/operation layer.

meager
  • 209,754
  • 38
  • 307
  • 315
0

We don't know the exact logic in your controller, but normally is a bad practice to include the logic in it. You should delegate all the business logic in the models.

From your controller you should only handle HTTP related things, and delegate to the correct model.

Assuming that this aproach is not the one for you, you can also use ActiveRecord Concerns, they are very usefull for DRY, allowing you to include little snippets of reutilizable code

If this even doesn't fit your requirements, you can put some .rb files in app_folder/lib, it's usually autoloaded, and you didn't need to require it manually

It would be very useful if you post the code of your controller, that would give us a better vision of what you are trying to do

Community
  • 1
  • 1
Hugo David Farji
  • 174
  • 2
  • 12