Sha256: eb39bbf2e5982eb10425a3f35eabd8595f10b8f17b35aefc1e31af248f4c1227

Contents?: true

Size: 1.1 KB

Versions: 3

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.camelcase] = 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

3 entries across 3 versions & 1 rubygems

Version Path
enlight-0.2.4 lib/enlight/requests/request.rb
enlight-0.2.3 lib/enlight/requests/request.rb
enlight-0.2.2 lib/enlight/requests/request.rb