Skip to content

Instantly share code, notes, and snippets.

@alexgriff
Created August 22, 2017 16:29
Show Gist options
  • Save alexgriff/1da25e0e32ecff5ef1678131e53fd1bf to your computer and use it in GitHub Desktop.
Save alexgriff/1da25e0e32ecff5ef1678131e53fd1bf to your computer and use it in GitHub Desktop.
Adapter Pattern
# How to think about the Single Responsibility Principle in your application...
# What part of your app has the responsibility of making the request to the API
# and turning the response into Ruby Objects & records in your database...?
# Not really the Models...
# ...And you may not want all the code that does this just intertwined within the logic of your app
# ... so where to put this code?
# That's what the Adapter Pattern is for.
# Make a class who's only responsibility is to get the data from the API
# and turn it into the format you want for your application
# Below is an example
module GoogleBooks
class Adapter
attr_reader :term
BASE_URL = "www.googleapis.com/books/v1/volumes"
def initialize(term = 'ruby programming')
@term = term
end
def create_books_and_authors
# make a request to the API
response = RestClient.get("#{BASE_URL}?q=#{self.term}")
data = JSON.parse(response.body)
#iterate over all the books in that response
data['items'].each do |book_data|
book = Book.find_or_initialize_by(title: book_data['volumeInfo']['title'], description: book_data['volumeInfo']['description'])
if book_data['volumeInfo']['authors']
author_name = book_data['volumeInfo']['authors'].first
author = Author.find_or_create_by(name: author_name)
end
# create and save the book objects and associated authors
book.author = author
book.save
end
end
end
end
# The code above could be used in your application like so:
# puts "Welcome to the Library Searcher"
# puts "Please Enter a search term:"
# query = gets.chomp
# GoogleBooks::Adapter.new(query).create_books_and_authors
# Here is a great blogpost on the Adapter Pattern, though it's in the context of Ruby on Rails
# http://www.thegreatcodeadventure.com/rails-refactoring-part-i-the-adapter-pattern/
# Ignore the parts you don't know (the Controller) and focus on the parts about the refactoring
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment