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, TypeFactory::NAMED_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.



30
31
32
# File 'lib/avro/builder/dsl.rb', line 30

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

Instance Method Details

#as_schemaObject



75
76
77
# File 'lib/avro/builder/dsl.rb', line 75

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

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

DSL methods for Types



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

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



53
54
55
56
# File 'lib/avro/builder/dsl.rb', line 53

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.



40
41
42
43
44
45
# File 'lib/avro/builder/dsl.rb', line 40

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



35
36
37
# File 'lib/avro/builder/dsl.rb', line 35

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.



60
61
62
# File 'lib/avro/builder/dsl.rb', line 60

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



65
66
67
68
69
70
71
72
73
# File 'lib/avro/builder/dsl.rb', line 65

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