Sha256: 9e80fd6e7eb0e159d5f9b0363c21d9ce0710f67b1bb2fdca8b46bac43c7132a2

Contents?: true

Size: 1.7 KB

Versions: 17

Compression:

Stored size: 1.7 KB

Contents

require 'bigdecimal'
require 'active_support/time'

class Gillbus
  class Parser

    attr_accessor :doc
    attr_accessor :instance
    attr_accessor :fields

    def initialize(instance:, doc:, fields:)
      @instance = instance
      @doc = doc
      @fields = fields
    end

    def parse
      fields.each do |name:, key:, type:, root:|
        raw_value =
          if key.is_a?(Regexp)
            doc.select { |k| k =~ key }
          elsif root
            doc[root] && doc[root][key]
          else
            doc[key]
          end
        value = make_one_or_many(type, raw_value)
        instance.send "#{name}=", value unless value.nil?
      end
      instance
    end

  private

    def make_one_or_many(type, val)
      # [:type]
      if type.is_a? Array
        array(val).map {|v| make_one type.first, v }
      # :type
      else
        make_one type, val
      end
    end

    def make_one(type, val)
      return if val.nil?
      if type.is_a? Class
        type.parse(val)
      else
        send type, val
      end
    end

    private

    # nil => []
    # [] => []
    # {} => [{}]
    def array(arg)
      return [arg] if arg.is_a? Hash
      Array(arg)
    end

    def string(val)
      return if val == "null"
      val
    end

    def bool(val)
      val == "true"
    end

    def yesno_bool(val)
      val == 'Y'
    end

    def int(val)
      val.to_i
    end

    def date(val)
      Date.strptime(val, '%d.%m.%Y')
    end

    def time(val)
      if val =~ /^ ( \d\d:\d\d ) (?: :\d\d )? $/x
        $1
      else
        nil
      end
    end

    def datetime(val)
      ActiveSupport::TimeZone["Europe/Kiev"].parse(val)
    end

    def decimal(val)
      BigDecimal.new(val)
    end

  end
end

Version data entries

17 entries across 17 versions & 1 rubygems

Version Path
gillbus-0.15.7 lib/gillbus/helpers/parser.rb
gillbus-0.15.6 lib/gillbus/helpers/parser.rb
gillbus-0.15.5 lib/gillbus/helpers/parser.rb
gillbus-0.15.4 lib/gillbus/helpers/parser.rb
gillbus-0.15.3 lib/gillbus/helpers/parser.rb
gillbus-0.15.2 lib/gillbus/helpers/parser.rb
gillbus-0.15.1 lib/gillbus/helpers/parser.rb
gillbus-0.15.0 lib/gillbus/helpers/parser.rb
gillbus-0.14.12 lib/gillbus/helpers/parser.rb
gillbus-0.14.11 lib/gillbus/helpers/parser.rb
gillbus-0.14.10 lib/gillbus/helpers/parser.rb
gillbus-0.14.9 lib/gillbus/helpers/parser.rb
gillbus-0.14.8 lib/gillbus/helpers/parser.rb
gillbus-0.14.7 lib/gillbus/helpers/parser.rb
gillbus-0.14.6 lib/gillbus/helpers/parser.rb
gillbus-0.14.5 lib/gillbus/helpers/parser.rb
gillbus-0.14.4 lib/gillbus/helpers/parser.rb