Sha256: e5d4abfe8db0305c6a53cb83fdd99c85327b02f404e94f309dafabd898325ca1

Contents?: true

Size: 1.08 KB

Versions: 4

Compression:

Stored size: 1.08 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)}
      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

4 entries across 4 versions & 1 rubygems

Version Path
enlight-0.1.4 lib/enlight/requests/request.rb
enlight-0.1.3 lib/enlight/requests/request.rb
enlight-0.1.2 lib/enlight/requests/request.rb
enlight-0.1.0 lib/enlight/requests/request.rb