Sha256: b2e0683a71598166663423cffffb00f95f737b0662e6f301491ade2c4c6df727

Contents?: true

Size: 1.97 KB

Versions: 1

Compression:

Stored size: 1.97 KB

Contents

require 'quandl/command/presenter/record'

require 'quandl/command/presenters/dataset_presenter'
require 'quandl/command/presenters/nil_class_presenter'
require 'quandl/command/presenters/error_presenter'
require 'quandl/command/presenters/scraper_presenter'
require 'quandl/command/presenters/superset_presenter'

module Quandl
module Command
class Presenter
  
  class << self
  
    def wrap_record_in_presenter(record, options)
      klass = find_presenter_for_record(record, options)
      klass.new(record, options)
    end
    
    def find_presenter_for_record(record, options={})
      name = 'Error' if record.kind_of?(Exception)
      name = options[:as] || record.class.name.to_s.split("::").last unless name.present?
      "Quandl::Command::Presenters::#{name}Presenter".constantize rescue Quandl::Command::Presenter::Record
    end
  
  end
  
  attr_accessor :options, :type
  
  def initialize( object, opts={} )
    self.type = ( object.try(:class) == Her::Collection ) ? :docs : :doc
    self.options = { type: type }.merge( opts.symbolize_keys! )
    self.collection = object
  end
  
  def each(&block)
    collection.each do |presenter|
      block.call( presenter )
    end
  end
  
  def each_to_format(type, &block)
    collection.each do |record|
      output = record.send("to_#{type}") if record.respond_to?("to_#{type}")
      block.call( output, record.object )
    end
  end
  
  def to_format(type)
    output = []
    collection.each do |record|
      output << record.send("to_#{type}") if record.respond_to?("to_#{type}")
    end
    output.join("\n")
  end
  
  def collection=(records)
    @collection = []
    records = Array(records).flatten
    records.each do |record|
      @collection << self.class.wrap_record_in_presenter(record, options)
    end
    # present nil if the collection is empty
    @collection = [self.class.wrap_record_in_presenter( nil, options )] if @collection.blank?
    @collection
  end
  
  def collection
    @collection ||= []
  end
  
end
end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
quandl-0.3.0 lib/quandl/command/presenter.rb