Class: AvroTurf::SchemaStore

Inherits:
Object
  • Object
show all
Defined in:
lib/avro_turf/schema_store.rb

Direct Known Subclasses

MutableSchemaStore

Instance Method Summary collapse

Constructor Details

#initialize(path: nil) ⇒ SchemaStore

Returns a new instance of SchemaStore.



3
4
5
6
7
# File 'lib/avro_turf/schema_store.rb', line 3

def initialize(path: nil)
  @path = path or raise "Please specify a schema path"
  @schemas = Hash.new
  @mutex = Mutex.new
end

Instance Method Details

#find(name, namespace = nil) ⇒ Object

Resolves and returns a schema.

schema_name - The String name of the schema to resolve.

Returns an Avro::Schema.



14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/avro_turf/schema_store.rb', line 14

def find(name, namespace = nil)
  fullname = Avro::Name.make_fullname(name, namespace)
  # Optimistic non-blocking read from @schemas
  # No sense to lock the resource when all the schemas already loaded
  return @schemas[fullname] if @schemas.key?(fullname)

  # Pessimistic blocking write to @schemas
  @mutex.synchronize do
    # Still need to check is the schema already loaded
    return @schemas[fullname] if @schemas.key?(fullname)

    load_schema!(fullname, @schemas.dup)
  end
end

#load_schemas!Object

Loads all schema definition files in the ‘schemas_dir`.



30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/avro_turf/schema_store.rb', line 30

def load_schemas!
  pattern = [@path, "**", "*.avsc"].join("/")

  Dir.glob(pattern) do |schema_path|
    # Remove the path prefix.
    schema_path.sub!(/^\/?#{@path}\//, "")

    # Replace `/` with `.` and chop off the file extension.
    schema_name = File.basename(schema_path.tr("/", "."), ".avsc")

    # Load and cache the schema.
    find(schema_name)
  end
end