class SakaiInfo::CLI::Lookup

Public Class Methods

process(args, flags) click to toggle source
# File lib/sakai-info/cli/lookup.rb, line 15
def self.process(args, flags)
  object_type = args.shift
  id = args.shift
  fields = nil
  output = :yaml

  flags_to_delete = []
  flags.each do |flag|
    if flag =~ /^--fields=(.+)$/
      fields = $1.downcase.split(',')
      flags_to_delete << flag
    elsif flag == "--json"
      output = :json
      flags_to_delete << flag
    end
  end

  flags_to_delete.each do |flag|
    flags.delete(flag)
  end

  if flags.include? "--all"
    serials = CLI::LookupModes[object_type].all_serializations
  elsif flags.include? "--dbrow-only"
    serials = [:dbrow_only]
  else
    serials = [:default] + flags.collect{|flag|flag.gsub(/^--/,'').gsub("-","_").to_sym}
  end

  object = nil
  begin
    object = CLI::LookupModes[object_type].find(id)
  rescue ObjectNotFoundException => e
    STDERR.puts "ERROR: #{e}"
    exit 1
  end

  if fields.nil? or fields.empty?
    if output == :json
      puts object.to_json(serials)
    else
      puts object.to_yaml(serials)
    end

  else
    object_hash = object.serialize(serials).delete_if{|k,v| not fields.include? k.to_s}
    if object_hash.empty?
      STDERR.puts "ERROR: no requested fields were found"
      exit 1
    end
    if output == :json
      puts object_hash.to_json
    else
      puts object_hash.to_yaml
    end
  end
end