module Quandl module Command class Presenter class Record attr_accessor :object, :options def initialize(*args) self.options = args.extract_options! self.object = args.first end # supported formats def to_format(f) self.send("to_#{f}") if self.respond_to?("to_#{f}") end def to_pipes column = options[:output_column] if options.present? && options.is_a?(Hash) pipes = as_pipes.dup.compact pipes = [ pipes[ column.to_i ] ] if column.present? && column.to_s.numeric? pipes.join(" | ") end def to_stderr as_stderr end def as_stderr output = '' output += "#{id}\n" if id.present? output += "#{detail}\n" if detail.present? output += errors if errors.present? output += object.to_s if object.kind_of?(Exception) output += object.backtrace.join("\n") if object.respond_to?(:backtrace) && options[:trace] == true output += "\n---\n" end def to_qdf object.try(:to_qdf) end def to_csv object.try(:to_csv) end def to_json as_json.try(:to_json) end def as_pipes [ status, id, detail, message ] end def as_json json = { status: status, id: id, detail: detail, message: message } json[:attributes] = object.attributes if object.respond_to?(:attributes) json[:metadata] = object.metadata if object.respond_to?(:metadata) json[:errors] = object.error_messages if object.respond_to?(:error_messages) json end # default attribute mappings def valid? return true if object.nil? return true if [200,201,404].include?(object.try(:status)) false end def status return Quandl::Client::HTTP_STATUS_CODES[422] if object.try(:errors).try(:present?) return object.try(:human_status) if object.respond_to?(:human_status) && object.human_status.present? Quandl::Client::HTTP_STATUS_CODES[404] end def id object.try(:id) end def message errors_without_spaces end def detail end def errors_without_spaces errors.to_s.gsub("\n", ' ') end def errors result = [] messages = object.try(:error_messages) || [] # extract repsonse errors re = messages.delete(:response_errors) if messages.is_a?(Hash) && messages.has_key?(:response_errors) re.each{|k,v| messages[k] = v } if re.present? && re.is_a?(Hash) # format messages.each do |k,v| v = v.join(" & ") if v.respond_to?(:join) result << "#{k}: #{v}" end result.join(", ") end def docs? options[:type] == :docs end def doc? options[:type] == :doc end end end end end