Class: Unitsdb::Database

Inherits:
Lutaml::Model::Serializable
  • Object
show all
Defined in:
lib/unitsdb/database.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.from_db(dir_path) ⇒ Object



280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
# File 'lib/unitsdb/database.rb', line 280

def self.from_db(dir_path)
  # If dir_path is a relative path, make it relative to the current working directory
  db_path = dir_path
  puts "Database directory path: #{db_path}"

  # Check if the directory exists
  raise Errors::DatabaseNotFoundError, "Database directory not found: #{db_path}" unless Dir.exist?(db_path)

  # Define required files
  required_files = %w[prefixes.yaml dimensions.yaml units.yaml quantities.yaml unit_systems.yaml]
  yaml_files = required_files.map { |file| File.join(dir_path, file) }

  # Check if all required files exist
  missing_files = required_files.reject { |file| File.exist?(File.join(dir_path, file)) }

  if missing_files.any?
    raise Errors::DatabaseFileNotFoundError,
          "Missing required database files: #{missing_files.join(", ")}"
  end

  # Ensure we have path properly joined with filenames
  prefixes_yaml = yaml_files[0]
  dimensions_yaml = yaml_files[1]
  units_yaml = yaml_files[2]
  quantities_yaml = yaml_files[3]
  unit_systems_yaml = yaml_files[4]

  # Debug paths
  if ENV["DEBUG"]
    puts "[UnitsDB] Loading YAML files from directory: #{dir_path}"
    puts "  - #{prefixes_yaml}"
    puts "  - #{dimensions_yaml}"
    puts "  - #{units_yaml}"
    puts "  - #{quantities_yaml}"
    puts "  - #{unit_systems_yaml}"
  end

  # Load YAML files with better error handling
  begin
    prefixes_hash = YAML.safe_load(File.read(prefixes_yaml))
    dimensions_hash = YAML.safe_load(File.read(dimensions_yaml))
    units_hash = YAML.safe_load(File.read(units_yaml))
    quantities_hash = YAML.safe_load(File.read(quantities_yaml))
    unit_systems_hash = YAML.safe_load(File.read(unit_systems_yaml))
  rescue Errno::ENOENT => e
    raise Errors::DatabaseFileNotFoundError, "Failed to read database file: #{e.message}"
  rescue Psych::SyntaxError => e
    raise Errors::DatabaseFileInvalidError, "Invalid YAML in database file: #{e.message}"
  rescue StandardError => e
    raise Errors::DatabaseLoadError, "Error loading database: #{e.message}"
  end

  # Verify all files have schema_version field
  missing_schema = []
  missing_schema << "prefixes.yaml" unless prefixes_hash.key?("schema_version")
  missing_schema << "dimensions.yaml" unless dimensions_hash.key?("schema_version")
  missing_schema << "units.yaml" unless units_hash.key?("schema_version")
  missing_schema << "quantities.yaml" unless quantities_hash.key?("schema_version")
  missing_schema << "unit_systems.yaml" unless unit_systems_hash.key?("schema_version")

  if missing_schema.any?
    raise Errors::DatabaseFileInvalidError,
          "Missing schema_version in files: #{missing_schema.join(", ")}"
  end

  # Extract versions from each file
  prefixes_version = prefixes_hash["schema_version"]
  dimensions_version = dimensions_hash["schema_version"]
  units_version = units_hash["schema_version"]
  quantities_version = quantities_hash["schema_version"]
  unit_systems_version = unit_systems_hash["schema_version"]

  # Check if all versions match
  versions = [
    prefixes_version,
    dimensions_version,
    units_version,
    quantities_version,
    unit_systems_version
  ]

  unless versions.uniq.size == 1
    version_info = {
      "prefixes.yaml" => prefixes_version,
      "dimensions.yaml" => dimensions_version,
      "units.yaml" => units_version,
      "quantities.yaml" => quantities_version,
      "unit_systems.yaml" => unit_systems_version
    }
    raise Errors::VersionMismatchError, "Version mismatch in database files: #{version_info.inspect}"
  end

  # Check if the version is supported
  version = versions.first
  unless version == "2.0.0"
    raise Errors::UnsupportedVersionError,
          "Unsupported database version: #{version}. Only version 2.0.0 is supported."
  end

  combined_yaml = {
    "schema_version" => prefixes_version,
    "prefixes" => prefixes_hash["prefixes"],
    "dimensions" => dimensions_hash["dimensions"],
    "units" => units_hash["units"],
    "quantities" => quantities_hash["quantities"],
    "unit_systems" => unit_systems_hash["unit_systems"]
  }.to_yaml

  from_yaml(combined_yaml)
end

Instance Method Details

#find_by_symbol(symbol, entity_type = nil) ⇒ Array

Find entities by symbol

Parameters:

  • symbol (String)

    the symbol to search for (exact match, case-insensitive)

  • entity_type (String, Symbol, nil) (defaults to: nil)

    the entity type to search (units or prefixes)

Returns:

  • (Array)

    entities with matching symbol



110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
# File 'lib/unitsdb/database.rb', line 110

def find_by_symbol(symbol, entity_type = nil)
  return [] unless symbol

  results = []

  # Symbol search only applies to units and prefixes
  collections = entity_type ? [entity_type.to_s] : %w[units prefixes]

  collections.each do |collection_name|
    next unless respond_to?(collection_name) && %w[units prefixes].include?(collection_name)

    collection = send(collection_name)
    collection.each do |entity|
      if collection_name == "units" && entity.respond_to?(:symbols) && entity.symbols
        # Units can have multiple symbols
        matches = entity.symbols.any? do |sym|
          sym.respond_to?(:ascii) && sym.ascii &&
            sym.ascii.downcase == symbol.downcase
        end

        results << entity if matches
      elsif collection_name == "prefixes" && entity.respond_to?(:symbols) && entity.symbols
        # Prefixes have multiple symbols in 2.0.0
        matches = entity.symbols.any? do |sym|
          sym.respond_to?(:ascii) && sym.ascii &&
            sym.ascii.downcase == symbol.downcase
        end

        results << entity if matches
      end
    end
  end

  results
end

#find_by_type(id:, type:) ⇒ Object?

Find an entity by its specific identifier and type

Parameters:

  • id (String)

    the identifier value to search for

  • type (String, Symbol)

    the entity type (units, prefixes, quantities, etc.)

Returns:

  • (Object, nil)

    the first entity with matching identifier or nil if not found



26
27
28
29
# File 'lib/unitsdb/database.rb', line 26

def find_by_type(id:, type:)
  collection = send(type.to_s)
  collection.find { |entity| entity.identifiers&.any? { |identifier| identifier.id == id } }
end

#get_by_id(id:, type: nil) ⇒ Object?

Find an entity by its identifier id across all entity types

Parameters:

  • id (String)

    the identifier value to search for

  • type (String, nil) (defaults to: nil)

    optional identifier type to match

Returns:

  • (Object, nil)

    the first entity with matching identifier or nil if not found



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/unitsdb/database.rb', line 35

def get_by_id(id:, type: nil)
  %w[units prefixes quantities dimensions unit_systems].each do |collection_name|
    next unless respond_to?(collection_name)

    collection = send(collection_name)
    entity = collection.find do |e|
      e.identifiers&.any? do |identifier|
        identifier.id == id && (type.nil? || identifier.type == type)
      end
    end

    return entity if entity
  end

  nil
end

#match_entities(params = {}) ⇒ Hash

Match entities by name, short, or symbol with different match types

Parameters:

  • params (Hash) (defaults to: {})

    match parameters

Options Hash (params):

  • :value (String)

    The value to match against

  • :match_type (String, Symbol)

    The type of match to perform (exact, symbol)

  • :entity_type (String, Symbol, nil)

    Optional entity type to limit search scope

Returns:

  • (Hash)

    matches grouped by match type (exact, symbol_match) with match details



152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
# File 'lib/unitsdb/database.rb', line 152

def match_entities(params = {})
  value = params[:value]
  match_type = params[:match_type]&.to_s || "exact"
  entity_type = params[:entity_type]

  return {} unless value

  result = {
    exact: [],
    symbol_match: []
  }

  # Define collections to search based on entity_type parameter
  collections = entity_type ? [entity_type.to_s] : %w[units prefixes quantities dimensions unit_systems]

  collections.each do |collection_name|
    next unless respond_to?(collection_name)

    collection = send(collection_name)

    collection.each do |entity|
      # For exact matches - look at short and names
      if %w[exact all].include?(match_type)
        # Match by short
        if entity.respond_to?(:short) && entity.short &&
           entity.short.downcase == value.downcase
          result[:exact] << {
            entity: entity,
            match_desc: "short_to_name",
            details: "UnitsDB short '#{entity.short}' matches '#{value}'"
          }
          next
        end

        # Match by names
        if entity.respond_to?(:names) && entity.names
          matching_name = entity.names.find { |name| name.value.to_s.downcase == value.downcase }
          if matching_name
            result[:exact] << {
              entity: entity,
              match_desc: "name_to_name",
              details: "UnitsDB name '#{matching_name.value}' (#{matching_name.lang}) matches '#{value}'"
            }
            next
          end
        end
      end

      # For symbol matches - only applicable to units and prefixes
      if %w[symbol all].include?(match_type) &&
         %w[units prefixes].include?(collection_name)
        if collection_name == "units" && entity.respond_to?(:symbols) && entity.symbols
          # Units can have multiple symbols
          matching_symbol = entity.symbols.find do |sym|
            sym.respond_to?(:ascii) && sym.ascii &&
              sym.ascii.downcase == value.downcase
          end

          if matching_symbol
            result[:symbol_match] << {
              entity: entity,
              match_desc: "symbol_match",
              details: "UnitsDB symbol '#{matching_symbol.ascii}' matches '#{value}'"
            }
          end
        elsif collection_name == "prefixes" && entity.respond_to?(:symbols) && entity.symbols
          # Prefixes have multiple symbols in 2.0.0
          matching_symbol = entity.symbols.find do |sym|
            sym.respond_to?(:ascii) && sym.ascii &&
              sym.ascii.downcase == value.downcase
          end

          if matching_symbol
            result[:symbol_match] << {
              entity: entity,
              match_desc: "symbol_match",
              details: "UnitsDB symbol '#{matching_symbol.ascii}' matches '#{value}'"
            }
          end
        end
      end
    end
  end

  # Remove empty categories
  result.delete_if { |_, v| v.empty? }

  result
end

#search(params = {}) ⇒ Array

Search for entities containing the given text in identifiers, names, or short description

Parameters:

  • params (Hash) (defaults to: {})

    search parameters

Options Hash (params):

  • :text (String)

    The text to search for

  • :type (String, Symbol, nil)

    Optional entity type to limit search scope

Returns:

  • (Array)

    all entities matching the search criteria



57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
# File 'lib/unitsdb/database.rb', line 57

def search(params = {})
  text = params[:text]
  type = params[:type]

  return [] unless text

  results = []

  # Define which collections to search based on type parameter
  collections = type ? [type.to_s] : %w[units prefixes quantities dimensions unit_systems]

  collections.each do |collection_name|
    next unless respond_to?(collection_name)

    collection = send(collection_name)
    collection.each do |entity|
      # Search in identifiers
      if entity.identifiers&.any? { |identifier| identifier.id.to_s.downcase.include?(text.downcase) }
        results << entity
        next
      end

      # Search in names (if the entity has names)
      if entity.respond_to?(:names) && entity.names && entity.names.any? do |name|
        name.value.to_s.downcase.include?(text.downcase)
      end
        results << entity
        next
      end

      # Search in short description
      if entity.respond_to?(:short) && entity.short &&
         entity.short.to_s.downcase.include?(text.downcase)
        results << entity
        next
      end

      # Special case for prefix name (prefixes don't have names array)
      next unless collection_name == "prefixes" && entity.respond_to?(:name) &&
                  entity.name.to_s.downcase.include?(text.downcase)

      results << entity
      next
    end
  end

  results
end

#validate_referencesObject

Validates references between entities



265
266
267
268
269
270
271
272
273
274
275
276
277
278
# File 'lib/unitsdb/database.rb', line 265

def validate_references
  invalid_refs = {}

  # Build registry of all valid IDs first
  registry = build_id_registry

  # Check various reference types
  check_dimension_references(registry, invalid_refs)
  check_unit_system_references(registry, invalid_refs)
  check_quantity_references(registry, invalid_refs)
  check_root_unit_references(registry, invalid_refs)

  invalid_refs
end

#validate_uniquenessObject

Checks for uniqueness of identifiers and short names



243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
# File 'lib/unitsdb/database.rb', line 243

def validate_uniqueness
  results = {
    short: {},
    id: {}
  }

  # Validate short names for applicable collections
  validate_shorts(units, "units", results)
  validate_shorts(dimensions, "dimensions", results)
  validate_shorts(unit_systems, "unit_systems", results)

  # Validate identifiers for all collections
  validate_identifiers(units, "units", results)
  validate_identifiers(prefixes, "prefixes", results)
  validate_identifiers(quantities, "quantities", results)
  validate_identifiers(dimensions, "dimensions", results)
  validate_identifiers(unit_systems, "unit_systems", results)

  results
end