Sha256: 6d911097e27b4c77da80a96194b8c4ea07fa4c7b15cfcacd429c31bc5221e022

Contents?: true

Size: 994 Bytes

Versions: 4

Compression:

Stored size: 994 Bytes

Contents

class Gillbus
  # Gives a bunch of class methods
  # to parse gillbus responses hash and define accessors
  #
  # Warning:
  #   resulting definitions won't work properly in subclass
  #
  # Usage:
  #     class MyClass
  #       extend Gillbus::Fields
  #       field :foo, :date
  #     end
  #
  #     MyClass.parse(hash)
  module Fields

    def parser_class
      if defined? @parser_class
        @parser_class || Gillbus::Parser
      else
        Gillbus::Parser
      end
    end

    def parse(doc, instance=new)
      parser_class.new(
        doc: doc,
        instance: instance,
        fields: field_definitions
      ).parse
      instance
    end

    def parser(&definition)
      @parser_class = Class.new(parser_class, &definition)
    end

    private

    def field_definitions
      @fields ||= []
    end

    def field(name, type=:string, key: name.to_s.upcase)
      field_definitions << {name: name, key: key, type: type}
      attr_accessor name
    end


  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
gillbus-0.14.3 lib/gillbus/helpers/fields.rb
gillbus-0.14.2 lib/gillbus/helpers/fields.rb
gillbus-0.14.1 lib/gillbus/helpers/fields.rb
gillbus-0.14.0 lib/gillbus/helpers/fields.rb