Alexandre Abreu
Alexandre Abreu

Reputation: 1417

Rails accessing an API

Im using Httparty to access COLOURlovers API. But im looking to do this in a rails way. I've managed it to work by creating a class on app/models/clover.rb:

require 'httparty'
class Clover
  include HTTParty

  base_uri 'www.colourlovers.com/api'

and then i've defined methods such as:

  def self.random(resource)
    fix_params query
    response = get("/#{resource}/random", { query: query })
    ActiveSupport::JSON.decode(response.body)
  end

then i query for a resource like:

Clover.random :color

It does the job, but im not sure this is a good way to solving this problem. Is there a design-pattern to this situation?

Upvotes: 0

Views: 95

Answers (1)

cpuguy83
cpuguy83

Reputation: 5993

I would extract the http stuff into its own class/module, including the parsing of the response, then inherit into your actual model class so the model is only ever dealing with the resource itself, not the the communication/parsing.

Upvotes: 1

Related Questions