Sha256: 3250eaa66f4592afca7fa608f141304d5c50b0a2a4b70e11e59b5ec1408fb7f2

Contents?: true

Size: 1.89 KB

Versions: 2

Compression:

Stored size: 1.89 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
              param = self.options[method_name]
              blank?(param) ? val : param
            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

2 entries across 2 versions & 1 rubygems

Version Path
vzaar-1.5.0 lib/vzaar/request/base.rb
vzaar-1.4.4 lib/vzaar/request/base.rb