Class: RubyBindgen::NameMapper
- Inherits:
-
Object
- Object
- RubyBindgen::NameMapper
- Defined in:
- lib/ruby-bindgen/name_mapper.rb
Class Method Summary collapse
-
.from_config(mappings) ⇒ Object
Factory: parses YAML config array of to: entries.
Instance Method Summary collapse
-
#initialize(mappings = []) ⇒ NameMapper
constructor
A new instance of NameMapper.
-
#lookup(*candidates) ⇒ Object
Look up a name, trying each candidate in order.
-
#merge(other) ⇒ Object
Merge two tables.
Constructor Details
#initialize(mappings = []) ⇒ NameMapper
Returns a new instance of NameMapper.
6 7 8 9 10 11 12 13 14 15 16 |
# File 'lib/ruby-bindgen/name_mapper.rb', line 6 def initialize(mappings = []) @exact = {} @regex = [] mappings.each do |pattern, replacement| if pattern.is_a?(Regexp) @regex << [pattern, replacement] else @exact[pattern] = replacement end end end |
Class Method Details
.from_config(mappings) ⇒ Object
Factory: parses YAML config array of to: entries
19 20 21 22 23 24 25 26 27 28 29 30 31 |
# File 'lib/ruby-bindgen/name_mapper.rb', line 19 def self.from_config(mappings) parsed = mappings.filter_map do |entry| key = entry[:from] || entry["from"] replacement = entry[:to] || entry["to"] next if key.nil? if key.start_with?('/') && key.end_with?('/') && key.length > 2 [Regexp.new(key[1..-2]), replacement] else [key, replacement] end end new(parsed) end |
Instance Method Details
#lookup(*candidates) ⇒ Object
Look up a name, trying each candidate in order. Returns the replacement value or nil.
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 |
# File 'lib/ruby-bindgen/name_mapper.rb', line 35 def lookup(*candidates) # O(1) exact match candidates.each do |name| result = @exact[name] return result if result end # Regex fallback @regex.each do |pattern, replacement| candidates.each do |name| if (m = pattern.match(name)) if replacement.is_a?(String) return replacement.gsub(/\\(\d+)/) { m[$1.to_i] } else return replacement end end end end nil end |
#merge(other) ⇒ Object
Merge two tables. Other’s entries override self’s.
58 59 60 61 62 |
# File 'lib/ruby-bindgen/name_mapper.rb', line 58 def merge(other) exact_mappings = @exact.merge(other.exact).map { |k, v| [k, v] } regex_mappings = other.regex + @regex self.class.new(exact_mappings + regex_mappings) end |