Sha256: 3c3184db70b300527e72835e28fbf023ce3dfcaa5310918a045f4120f589f250

Contents?: true

Size: 1.87 KB

Versions: 1

Compression:

Stored size: 1.87 KB

Contents

module SirenClient
  class Action
    include Modules::WithRawResponse

    attr_accessor :href
    attr_reader :payload, :name, :classes, :method, :title, :type, :fields, :config

    def initialize(data, config={})
      super()
      if data.class != Hash
        raise ArgumentError, "You must pass in a Hash to SirenClient::Action.new"
      end
      @payload = data

      @config = { format: :json }.merge config
      @name    = @payload['name']   || ''
      @classes = (@payload['class']  || []).clone
      @method  = (@payload['method'] || 'GET').downcase
      @href    = @payload['href']   || ''
      @title   = @payload['title']  || ''
      @type    = @payload['type']   || 'application/x-www-form-urlencoded'
      @fields  = (@payload['fields'] || []).clone
      @fields.map! do |field_data|
        SirenClient::Field.new(field_data)
      end
    end

    def where(params = {})
      options = { headers: {} }.merge @config
      if @method == 'get'
        options[:query] = params
      else
        options[:body] = params

        # Only set the Content-Type if we have a body
        options[:headers]['Content-Type'] = @type
      end

      begin
        resp = generate_raw_response(@method, self.href, options)
        if next_response_is_raw?
          disable_raw_response
          resp
        else
          if resp.parsed_response.nil?
            raise InvalidResponseError.new "Response could not be parsed. Code=#{resp.code} Message=\"#{resp.message}\" Body=#{resp.body}"
          end
          Entity.new(resp.parsed_response, @config)
        end
      rescue URI::InvalidURIError => e
        raise InvalidURIError, e.message
      rescue JSON::ParserError => e
        raise InvalidResponseError, e.message
      end
    end
    # `.submit` should be used with actions that
    # don't require any parameters, for readability.
    alias_method :submit, :where
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
siren_client-2.0.1 lib/siren_client/action.rb