Reputation: 2045
Following is my use case -
I have a controller method(action) that makes an API call to Google. I have created a class Google
which I have put in lib
folder. Class Google
provides the api call method.
def self.list_items(folder_id, access_token)
result = RestClient.get "#{API_URL}/drive/v2/files",
{
:Authorization => "Bearer #{access_token}",
:params => {:q => "'#{folder_id}' in parents and trashed=false"}
}
return JSON.parse(result)['items']
end
However, I need to write a method that calls list_items
from Google
, catches exception in case access_token expires, refreshes access_token, saves the new access_token in database and makes the list_items
call again.
Since this method needs to interact with database, I don't want to put it in a class in lib
. I am new to rails, and I have understood that lib
folder should have third party code. Class Google
here can be considered a third party class as its a PORO without anything to do with rails project or my business logic. Please correct me if this understanding is wrong.
I can keep this method as a private method in controller, but assume there are multiple such methods. Won't that make the controller fat?
Also, the controller is FileApiController
, while all these methods are google specific. I also have methods specific to box and dropbox. I would ideally like to create GoogleHelper
, DropboxHelper
etc. classes, which interact with db as well. Where to keep this classes?
I come from Grails background, and GoogleHelper
would typically be made as a service in Grails like googleService. What is the rails way of doing it. Specifically, if I make a GoogleHelper
class, where to keep it? I guess, helper folder is only to keep view helpers.
Upvotes: 1
Views: 160
Reputation: 6311
Create file in app/helpers/google_helper.rb
module GoogleHelper
class << self
def print_hello
puts 'HELLO WORLD'
end
def list_items(folder_id, access_token)
result = RestClient.get "#{API_URL}/drive/v2/files",
{
:Authorization => "Bearer #{access_token}",
:params => {:q => "'#{folder_id}' in parents and trashed=false"}
}
return JSON.parse(result)['items']
end
end
end
If you want to call GoogleHelper
in controllers then add it in application_controller.rb
this include GoogleHelper
Now you can call your helper: GoogleHelper.print_hello
in a controller.
Upvotes: 3