Class: Avro::Builder::DSL

Inherits:
Object
  • Object
show all
Includes:
DslAttributes, DslOptions, FileHandler, TypeFactory
Defined in:
lib/avro/builder/dsl.rb

Overview

This class is used to construct Avro schemas (not protocols) using a ruby DSL

Constant Summary

Constants included from TypeFactory

TypeFactory::BUILTIN_TYPES, TypeFactory::COMPLEX_TYPES

Instance Method Summary collapse

Methods included from FileHandler

included, #read_file

Methods included from DslAttributes

#dsl_attribute?, included

Methods included from DslOptions

#dsl_option?, included

Constructor Details

#initialize(str = nil, &block) ⇒ DSL

An instance of the DSL is initialized with a string or a block to evaluate to define Avro schema objects.



27
28
29
# File 'lib/avro/builder/dsl.rb', line 27

def initialize(str = nil, &block)
  str ? instance_eval(str) : instance_eval(&block)
end

Instance Method Details

#as_schemaObject



72
73
74
# File 'lib/avro/builder/dsl.rb', line 72

def as_schema
  Avro::Schema.parse(to_json(validate: false))
end

#enum(name = nil, *symbols, **options, &block) ⇒ Object

DSL methods for Types



46
47
48
# File 'lib/avro/builder/dsl.rb', line 46

def enum(name = nil, *symbols, **options, &block)
  create_named_type(name, :enum, { symbols: symbols }.merge(options), &block)
end

#fixed(name = nil, size = nil, options = {}, &block) ⇒ Object



50
51
52
53
# File 'lib/avro/builder/dsl.rb', line 50

def fixed(name = nil, size = nil, options = {}, &block)
  size_option = size.is_a?(Hash) ? size : { size: size }
  create_named_type(name, :fixed, size_option.merge(options), &block)
end

#import(name) ⇒ Object

Imports from the file with specified name fragment.



37
38
39
40
41
42
# File 'lib/avro/builder/dsl.rb', line 37

def import(name)
  previous_namespace = namespace
  result = eval_file(name)
  namespace(previous_namespace)
  result
end

#record(name = nil, options = {}, &block) ⇒ Object

Define an Avro schema record



32
33
34
# File 'lib/avro/builder/dsl.rb', line 32

def record(name = nil, options = {}, &block)
  create_named_type(name, :record, options, &block)
end

#to_hObject

Return the last schema object processed as a Hash representing the Avro schema.



57
58
59
# File 'lib/avro/builder/dsl.rb', line 57

def to_h
  @last_object.to_h(SchemaSerializerReferenceState.new)
end

#to_json(validate: true, pretty: true) ⇒ Object

Return the last schema object processed as an Avro JSON schema



62
63
64
65
66
67
68
69
70
# File 'lib/avro/builder/dsl.rb', line 62

def to_json(validate: true, pretty: true)
  hash = to_h
  (pretty ? JSON.pretty_generate(hash) : hash.to_json).tap do |json|
    # Uncomment the next line to debug:
    # puts json
    # Parse the schema to validate before returning
    ::Avro::Schema.parse(json) if validate
  end
end