Sha256: cba8509a049f24fbb9c517c65395e54b7ab8d6be2436d36852f72c1e1b6d00e1

Contents?: true

Size: 1.1 KB

Versions: 2

Compression:

Stored size: 1.1 KB

Contents

require 'net/http'
require 'active_support/all'

module Enlight
  module Requests
    class Request
      attr_accessor :id

      def initialize(attributes = {})
        attributes.each {|k,v| send("#{k}=", v) if respond_to?(k)}
      end

      def fetch
        data = JSON.parse(Net::HTTP.get(build_uri))

        "Enlight::Responses::#{resource}".constantize.new(data)
      end

      def resource
        self.class.to_s.split("::").last
      end

      def build_uri
        query_params = {}
        resource_id = nil

        instance_variables.each do |v|
          var = v.to_s.delete('@')

          if var == 'id'
            resource_id = instance_variable_get(v) if var == 'id'
          else
            query_params[var.classify] = instance_variable_get(v)
          end
        end

        uri = "#{base_uri}/#{resource}"
        uri += "/#{resource_id}" if resource_id
        uri += "?#{query_params.to_query}" if query_params.any?

        URI(uri)
      end

      private

      def base_uri
        URI("#{Enlight.configuration.url}/#{Enlight.configuration.integration_key}")
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
enlight-0.2.1 lib/enlight/requests/request.rb
enlight-0.2.0 lib/enlight/requests/request.rb