class Chinacity::Cli

Public Class Methods

new(options) click to toggle source
# File lib/chinacity/cli.rb, line 14
def initialize options
  @short    = options[:short]
  @foramt   = options[:format]
  @minimize = options[:minimize]
  @headless = options[:headless]
end

Public Instance Methods

start() click to toggle source
# File lib/chinacity/cli.rb, line 21
def start
  doc = Nokogiri::HTML(get_data)
  get_cities(doc)

  add_short_name if @short

  @foramt == :json ? output_json : output_csv
end

Private Instance Methods

add_short_name() click to toggle source
# File lib/chinacity/cli.rb, line 52
def add_short_name
  @cities.each do |city|
    # puts city
    city[:short] = Pinyin.t(city[:text]).split.map{|w|w[0]}.join.upcase
  end

  self
end
get_cities(doc) click to toggle source
# File lib/chinacity/cli.rb, line 44
def get_cities(doc)
  @cities = doc.css('p.MsoNormal').map do |data|
    id, text = data.text.gsub(/[[:space:]]+/, ' ').split

    {id: id, text: text} if id
  end.compact
end
get_data() click to toggle source
# File lib/chinacity/cli.rb, line 31
def get_data
  # puts LIST_URL

  # get newest city url
  data = HTTParty.get(LIST_URL).body
  doc = Nokogiri::HTML data
  url = LIST_URL + doc.css('.center_list a')[0][:href]
  # puts url

  # get newest city data
  HTTParty.get(url).body
end
nested_cities() click to toggle source
# File lib/chinacity/cli.rb, line 61
def nested_cities
  pretty = {}

  @cities.each do |city|
    if city[:id].end_with? '0000'
      pretty[:province] ||= []
      pretty[:province] << city
    elsif city[:id].end_with? '00'
      pretty[:city] ||= []
      pretty[:city] << city
    else
      pretty[:district] ||= []
      pretty[:district] << city
    end
  end

  pretty
end
output_csv() click to toggle source
# File lib/chinacity/cli.rb, line 88
def output_csv
  CSV do |csv_out|
    unless @headless
      list = @short ? ["id", "名称", "缩写", "层级"] : ["id", "名称", "层级"]
      csv_out << list
    end

    @cities.map do |city|
      level = if city[:id].end_with? '0000'
        1
      elsif city[:id].end_with? '00'
        2
      else
        3
      end

      list = @short ? [city[:id], city[:text], city[:short], level] : [city[:id], city[:text], level]

      csv_out << list
    end
  end
end
output_json() click to toggle source
# File lib/chinacity/cli.rb, line 80
def output_json
  if @minimize
    STDOUT.write JSON.generate(nested_cities)
  else
    STDOUT.write JSON.pretty_generate(nested_cities)
  end
end