How to refactor code into a service class

Viewed 98

I have logic in my model that I think would better be fit into a service class. It grabs a list of movies from an API. Ideally, I'd like this service class to do the same and seed the database. Currently, I call Movie.create_all_from_api in the seeds.rb file. I'm new to Rails so I'm wondering where to put this service class and where I should call the service. Do I put it in a /app/service folder?

Movie.rb

class Movie < ApplicationRecord
   require 'rest_client'
   has_many :reviews

   def self.create_all_from_api
      moviedata = retrieve_results
      moviedata['results'].each do |m|
        Movie.create(title: m['title'], release: m['release_date'], genre: m['genre'])
      end
   end

   def self.get_data(url)
      RestClient.get(url, { :content_type => :json})
   end

   def self.retrieve_results
      url = "https://api.themoviedb.org/3/movie/popular?page=1&language=en-US&api_key=s0m3n1c3k3y"
      JSON.parse(get_data(url))
   end

end

My proposed service class

class ApiService
   require 'rest_client'
   def self.create_all_from_api
      moviedata = retrieve_results
      moviedata['results'].each do |m|
         Movie.create(title: m['title'], release: m['release_date'], genre: m['genre'])
      end
   end

   def self.get_data(url)
      RestClient.get(url, { :content_type => :json})
   end

   def self.retrieve_results
      url = "https://api.themoviedb.org/3/movie/popular?page=1&language=en-US&api_key=s0m3n1c3k3y"
      JSON.parse(get_data(url))
   end
end
1 Answers
Related