简体   繁体   中英

How to write and include regular ruby classes in rails

I'm learning Rails. I have a controller responsible for presenting data from parsing files uploaded by the user. I don't want the data to be stored anywhere in the model. Can I include a class that I can instantiate in my controller method? Here is a basic code example of what I mean:

This controller only contains one method:

class MyController < ApplicationController
    def index
        test = FileProcessorService.new
        @test = test.test()
    end
end

Here is the class that will handle the logic when the instantiates calls its method:

class FileProcessorService
    def test
        return 'This is a test'
    end
end

My questions:

Where is the best place to store this class? How can I refer to this class in my controller? Any advice on this particular topic of using classes in rails? Are instances of a regular ruby class a problem in the controller? I dont want my users seeing the same data. Thats why I dont want to include global variables in my controller. No models since I have an MVC back ground with Java MVC. I'll move on to models once I understand how the basic rails controller functionality works.

Thank you in advance for your help.

I usually put these in app/classes , or if there are a lot of them, into more specific folders likes app/services , app/notifiers , etc.

You can enable autoloading in config/application.rb :

config.autoload_paths += %W(#{config.root}/app/classes #{config.root}/app/services)

If they're not application-specific, extract them to a gem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM