Class: BetterTranslate::Analyzer::KeyScanner
- Inherits:
-
Object
- Object
- BetterTranslate::Analyzer::KeyScanner
- Defined in:
- lib/better_translate/analyzer/key_scanner.rb
Overview
Scans YAML translation files and extracts all keys in flatten format
Instance Attribute Summary collapse
-
#file_path ⇒ String
readonly
Path to the YAML file.
-
#keys ⇒ Hash
readonly
Flatten keys extracted from YAML.
Instance Method Summary collapse
-
#flatten_keys(hash, prefix = nil) ⇒ Object
private
Flatten nested hash into dot-notation keys.
-
#initialize(file_path) ⇒ KeyScanner
constructor
Initialize scanner with YAML file path.
-
#key_count ⇒ Integer
Get total count of keys.
-
#scan ⇒ Hash
Scan YAML file and extract all flatten keys.
-
#validate_file! ⇒ Object
private
Validate that file exists.
Constructor Details
#initialize(file_path) ⇒ KeyScanner
Initialize scanner with YAML file path
25 26 27 28 |
# File 'lib/better_translate/analyzer/key_scanner.rb', line 25 def initialize(file_path) @file_path = file_path @keys = {} end |
Instance Attribute Details
#file_path ⇒ String (readonly)
Returns Path to the YAML file.
16 17 18 |
# File 'lib/better_translate/analyzer/key_scanner.rb', line 16 def file_path @file_path end |
#keys ⇒ Hash (readonly)
Returns Flatten keys extracted from YAML.
19 20 21 |
# File 'lib/better_translate/analyzer/key_scanner.rb', line 19 def keys @keys end |
Instance Method Details
#flatten_keys(hash, prefix = nil) ⇒ Object (private)
Flatten nested hash into dot-notation keys
96 97 98 99 100 101 102 103 104 105 106 |
# File 'lib/better_translate/analyzer/key_scanner.rb', line 96 def flatten_keys(hash, prefix = nil) hash.each do |key, value| current_key = prefix ? "#{prefix}.#{key}" : key.to_s if value.is_a?(Hash) flatten_keys(value, current_key) else @keys[current_key] = value end end end |
#key_count ⇒ Integer
Get total count of keys
68 69 70 |
# File 'lib/better_translate/analyzer/key_scanner.rb', line 68 def key_count @keys.size end |
#scan ⇒ Hash
Scan YAML file and extract all flatten keys
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 |
# File 'lib/better_translate/analyzer/key_scanner.rb', line 41 def scan validate_file! begin content = YAML.load_file(file_path) # Skip root language key (en, it, fr, etc.) and start from its content if content.is_a?(Hash) && content.size == 1 root_key = content.keys.first.to_s content = content[root_key] || {} if root_key.match?(/^[a-z]{2}(-[A-Z]{2})?$/) end flatten_keys(content) rescue Psych::SyntaxError => e raise YamlError.new( "Invalid YAML syntax in #{file_path}", context: { file: file_path, error: e. } ) end @keys end |
#validate_file! ⇒ Object (private)
Validate that file exists
78 79 80 81 82 83 84 85 |
# File 'lib/better_translate/analyzer/key_scanner.rb', line 78 def validate_file! return if File.exist?(file_path) raise FileError.new( "Translation file does not exist: #{file_path}", context: { file: file_path } ) end |