Sha256: f3875acd1a89bf419252b3865cb6d997f0c63b5775d9390ae098ab857bb43d38

Contents?: true

Size: 1.74 KB

Versions: 2

Compression:

Stored size: 1.74 KB

Contents

require "net/https"
require "xmlsimple"

module Bisu
  module Source
    class GoogleSheet
      def initialize(sheet_id, keys_column)
        @sheet_id = sheet_id
        @key_column = keys_column
      end

      def to_i18
        raw = raw_data(@sheet_id)

        Logger.info("Downloading dictionary from Google Sheet...")

        non_language_columns = ["id", "updated", "category", "title", "content", "link", @key_column]

        kb = {}
        raw["entry"].each do |entry|
          unless (key = entry[@key_column]) && key = key.first
            raise "Cannot find key column '#{@key_column}'"
          end

          entry.select { |c| !non_language_columns.include?(c) }.each do |lang, texts|
            kb[lang] ||= {}
            kb[lang][key] = texts.first unless texts.first == {}
          end
        end

        Logger.info("Google Sheet parsed successfully!")
        Logger.info("Found #{kb.count} languages.")

        kb
      end

      private

      def xml_data(uri, headers=nil)
        uri = URI.parse(uri)
        http = Net::HTTP.new(uri.host, uri.port)
        http.use_ssl = true
        http.verify_mode = OpenSSL::SSL::VERIFY_NONE
        data = http.get(uri.path, headers)

        unless data.code.to_i == 200
          raise "Cannot access sheet at #{uri} - HTTP #{data.code}"
        end

        begin
          XmlSimple.xml_in(data.body, 'KeyAttr' => 'name')
        rescue
          raise "Cannot parse. Expected XML at #{uri}"
        end
      end

      def raw_data(sheet_id)
        Logger.info("Downloading Google Sheet...")
        sheet = xml_data("https://spreadsheets.google.com/feeds/worksheets/#{sheet_id}/public/full")
        url   = sheet["entry"][0]["link"][0]["href"]
        xml_data(url)
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
bisu-1.6.0 lib/bisu/source/google_sheet.rb
bisu-1.5.0 lib/bisu/source/google_sheet.rb