class Wpcli::Client

Public Class Methods

new(path = "") click to toggle source
# File lib/wpcli/client.rb, line 3
def initialize path = ""
  @path = path
end

Public Instance Methods

run(command) click to toggle source
# File lib/wpcli/client.rb, line 6
def run command
  output = `wp#{@path.empty? ? " " : " --path=" + @path + " "}#{command}`
  parse output
end

Private Instance Methods

detect_if_line_is_from_single_value_response() click to toggle source
# File lib/wpcli/client.rb, line 66
def detect_if_line_is_from_single_value_response
  @columns.each do |column|
    return true if !column.nil? && column.strip.downcase == "field"
  end
  false
end
is_blank?(string) click to toggle source
# File lib/wpcli/client.rb, line 43
def is_blank? string
  string == nil || string.empty?
end
parse(text) click to toggle source
# File lib/wpcli/client.rb, line 13
def parse text
  lines = text.split("\n")
  return text.strip if lines.size == 1

  single_value = false
  first_data_row = starts_with_plus?(text) ? 3 : 1
  rows = []
  lines.each_with_index do |line, index|
    unless is_blank?(line) || starts_with_plus?(line)
      separator = line.include?('|') ? '|' : "\t"
      if index < first_data_row
        @columns = parse_header line, separator
        single_value = detect_if_line_is_from_single_value_response
      else
        if single_value
          parsed_line = parse_line(line, separator)
          value = parsed_line[:value]
          unless value.nil? || value == "null"
            rows << {} unless rows.size == 1
            rows.first[parsed_line[:field].to_sym] = value
          end
        else
          rows << parse_line(line, separator)
        end
      end
    end
  end
  rows
end
parse_header(line, separator) click to toggle source
# File lib/wpcli/client.rb, line 47
def parse_header line, separator
  columns = []
  line.split(separator).each_with_index do |column, index|
    columns[index] = column.strip.downcase unless column.strip.empty?
  end
  columns
end
parse_line(line, separator) click to toggle source
# File lib/wpcli/client.rb, line 54
def parse_line line, separator
  hash = {}
  line.split(separator).each_with_index do |column, index|
    hash[@columns[index].to_sym] = column.strip unless @columns[index].nil?
  end
  hash
end
starts_with_plus?(line) click to toggle source
# File lib/wpcli/client.rb, line 62
def starts_with_plus? line
  line.start_with? "+"
end