Sha256: e9799952dfcad6abbe5dfc35edf6bf3cc35d3e0e87bd2f72e6674615dc46dadf

Contents?: true

Size: 1.86 KB

Versions: 5

Compression:

Stored size: 1.86 KB

Contents

module Vzaar
  module Request
    class Base < Struct.new(:conn, :opts)
      include Vzaar::Helper

      class << self
        [:authenticated, :http_verb].each do |method_name|
          define_method(method_name) do |val|
            define_method(method_name) do
              val.nil? ? self.options[method_name] : val
            end
          end
        end

        def endpoint(obj=nil, &fn)
          define_method(:endpoint) { block_given? ? yield(self) : obj }
        end

        def resource(name)
          define_method(:resource) { name }
        end

        def format(f)
          define_method(:format) do
            # JC: options should always overwrite format param
            self.options[:format] ? self.options[:format] : f
          end
        end
      end

      authenticated nil
      http_verb :get
      format :xml

      def execute
        conn.using_connection(url, user_options) do |res|
          _res = Response::Base.new(res)
          if _res.json?
            return _res.body
          else
            return resource_klass.new(_res.body, res.code)
          end
        end
      end

      protected

      attr_reader :xml_body, :json_body

      def resource_klass
        name = resource.is_a?(Symbol) ? resource.to_s.capitalize : resource
        Resource.const_get(name)
      end

      def options
        @options ||= symb_keys(opts)
      end

      def format_suffix
        format
      end

      def url
        Url.new(endpoint, format_suffix, url_params).build
      end

      def user_options
        { format: format.to_sym,
          authenticated: authenticated,
          http_verb: http_verb,
          data: data
        }
      end

      def xml?
        format == :xml
      end

      def url_params
        options[:params] || {}
      end

      def data
        xml? ? xml_body : json_body
      end
    end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
vzaar-1.4.1 lib/vzaar/request/base.rb
vzaar-1.3.1 lib/vzaar/request/base.rb
vzaar-1.3.0 lib/vzaar/request/base.rb
vzaar-1.2.4 lib/vzaar/request/base.rb
vzaar-1.2.3 lib/vzaar/request/base.rb