Skip to content
This repository
tree: fa63fb9a27
Fetching contributors…

Octocat-spinner-32-eaf2f5

Cannot retrieve contributors at this time

file 90 lines (73 sloc) 2.194 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
require 'faraday_stack'
require 'hashie/mash'

module Instagram
  module Configuration
    attr_accessor :client_id, :client_secret, :access_token, :cache
  
    def configure
      yield self
    end
  end
  
  class Mashify < Faraday::Response::Middleware
    def on_complete(env)
      super if Hash === env[:body]
    end
    
    def parse(body)
      Hashie::Mash.new(body)
    end
  end
  
  class PreserveRawBody < Faraday::Response::Middleware
    def on_complete(env)
      env[:raw_body] = env[:body]
    end
  end
  
  module Connection
    def connection
      @connection ||= begin
        conn = Faraday.new('https://api.instagram.com/v1/') do |b|
          b.use Mashify
          b.use FaradayStack::ResponseJSON, content_type: 'application/json'
          b.use PreserveRawBody
          b.use FaradayStack::Caching, cache, strip_params: %w[access_token client_id] unless cache.nil?
          b.response :raise_error
          b.use FaradayStack::Instrumentation
          b.adapter Faraday.default_adapter
        end
      
        # conn.token_auth access_token unless access_token.nil?
        conn.params['access_token'] = access_token unless access_token.nil?
        conn.params['client_id'] = client_id
        conn.headers['User-Agent'] = 'instagram.heroku.com ruby client'
      
        conn
      end
    end
    
    def get(path, params = nil)
      connection.get(path) do |request|
        request.params = params if params
      end
    end
  end
  
  module ApiMethods
    def get(path, params = nil)
      raw = params && params.delete(:raw)
      response = super
      raw ? response.env[:raw_body] : response.body.data
    end
    
    def user(user_id, *args)
      get("users/#{user_id}", *args)
    end
  
    def user_recent_media(user_id, *args)
      get("users/#{user_id}/media/recent", *args)
    end
  
    def media_popular(*args)
      get("media/popular", *args)
    end
  
    def tag_search(query, params = {})
      get("tags/search", params.merge(:q => query))
    end
  
    def tag_recent_media(tag, *args)
      get("tags/#{tag}/media/recent", *args)
    end
  end
  
  extend Configuration
  extend Connection
  extend ApiMethods
end
Something went wrong with that request. Please try again.