Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 509
Horse Voice Avatar asked Mar 06 '14 02:03

Horse Voice


People also ask

Can you include a class in Ruby?

Ruby allows you to create a class tied to a particular object. In the following example, we create two String objects. We then associate an anonymous class with one of them, overriding one of the methods in the object's base class and adding a new method.

How do you create a class in Ruby?

In Ruby, one can easily create classes and objects. Simply write class keyword followed by the name of the class. The first letter of the class name should be in capital letter.

How do you call a class from a different file in Ruby?

To put a class in a separate file, just define the class as usual and then in the file where you wish to use the class, simply put require 'name_of_file_with_class' at the top. For instance, if I defined class Foo in foo. rb , in bar. rb I would have the line require 'foo' .


1 Answers

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.

like image 156
Zach Kemp Avatar answered Oct 01 '22 18:10

Zach Kemp