Module: SchemaTools::Modules::Read

Included in:
Reader, Reader
Defined in:
lib/schema_tools/modules/read.rb

Overview

Read schemas into a hash

Instance Method Summary collapse

Instance Method Details

#read(schema_name, path_or_schema = nil) ⇒ Object

Read a schema and return it as hash. You can supply a path or the global path defined in #SchemaTools.schema_path is used. Schemata returned from cache in #registry to prevent filesystem round-trips. The cache can be resented with #registry_reset

@return schema as hash

Parameters:

  • schema (String|Symbol)

    name to be read from schema path directory

  • either (String|Hash)

    the path to retrieve schema_name from, or a Schema in Ruby hash form



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/schema_tools/modules/read.rb', line 35

def read(schema_name, path_or_schema=nil)
  schema_name = schema_name.to_sym
  return registry[schema_name] if registry[schema_name]

  if path_or_schema.is_a? ::Hash
    path       = nil
    plain_data = path_or_schema.to_json
  elsif path_or_schema.is_a?(::String) || path_or_schema.nil?
    path       = path_or_schema
    file_path  = File.join(path || SchemaTools.schema_path, "#{schema_name}.json")
  else
    raise ArgumentError, "Second parameter must be a path or a schema!"
  end

  plain_data ||= File.open(file_path, 'r'){|f| f.read}

  schema = ActiveSupport::JSON.decode(plain_data).with_indifferent_access
  if schema[:extends]
    extends = schema[:extends].is_a?(Array) ? schema[:extends] : [ schema[:extends] ]
    extends.each do |ext_name|
      ext = read(ext_name, path)
      # current schema props win
      schema[:properties] = ext[:properties].merge(schema[:properties])
    end
  end
  registry[ schema_name ] = schema
end

#read_all(path = nil) ⇒ Array<HashWithIndifferentAccess>

Read all available schemas from a given path(folder) and return them as array

Parameters:

  • path (String) (defaults to: nil)

    to schema files

Returns:

  • (Array<HashWithIndifferentAccess>)

    array of schemas as hash



68
69
70
71
72
73
74
75
76
# File 'lib/schema_tools/modules/read.rb', line 68

def read_all(path=nil)
  schemas = []
  file_path = File.join(path || SchemaTools.schema_path, '*.json')
  Dir.glob( file_path ).each do |file|
    schema_name = File.basename(file, '.json').to_sym
    schemas << read(schema_name, path)
  end
  schemas
end

#registryHash{String=>Hash{Symbol=>HashWithIndifferentAccess}}

Variable remembering already read-in schema’s

:invoice =>{schema
:credit_note =>schema
}

}

Returns:

  • (Hash{String=>Hash{Symbol=>HashWithIndifferentAccess}})


18
19
20
# File 'lib/schema_tools/modules/read.rb', line 18

def registry
  @registry ||= {}
end

#registry_resetObject



22
23
24
# File 'lib/schema_tools/modules/read.rb', line 22

def registry_reset
  @registry = nil
end