Sha256: 83c75498475e6a746e0193913c3ba57e3600707ee3e6cf2bd90e2592fababfc0

Contents?: true

Size: 1.39 KB

Versions: 8

Compression:

Stored size: 1.39 KB

Contents

require 'pupper/parse_json'

module Pupper
  # Provides an interface to build an API Client, that can be used by [Model]
  class Backend
    class BaseUrlNotDefined < StandardError; end

    attr_reader :client, :model

    delegate :base_url, to: :class

    class << self
      # Sets the base URL the API client will call
      # @return [String] the URL (plus - optionally - a path)
      attr_writer :base_url

      def base_url
        if @base_url.nil?
          raise BaseUrlNotDefined, <<-ERR
            Add the following to #{name} to make it work:

              self.base_url = "https://example.com/some/path"

            Making sure to change the URL to something useful :)))
          ERR
        end

        @base_url
      end
    end

    %i(get put post delete patch).each do |name|
      class_eval <<-RB.strip_heredoc, __FILE__, __LINE__
        def #{name}(*args)
          client.send(:#{name}, *args).body
        end
      RB
    end

    def initialize
      @client = Faraday.new(base_url, ssl: { verify: Rails.env.production? }) do |builder|
        builder.request :json
        builder.use Pupper::ParseJson
        builder.response :logger if Rails.env.development?
        builder.response :raise_error
        builder.adapter :typhoeus
        builder.headers['User-Agent'] = Pupper.config.user_agent
      end
    end

    def register_model(model)
      @model = model
    end
  end
end

Version data entries

8 entries across 8 versions & 1 rubygems

Version Path
pupper-0.1.13 lib/pupper/backend.rb
pupper-0.1.12 lib/pupper/backend.rb
pupper-0.1.11 lib/pupper/backend.rb
pupper-0.1.10 lib/pupper/backend.rb
pupper-0.1.9 lib/pupper/backend.rb
pupper-0.1.8 lib/pupper/backend.rb
pupper-0.1.7 lib/pupper/backend.rb
pupper-0.1.6 lib/pupper/backend.rb