Class: RubyJard::KeyBindings
- Inherits:
-
Object
- Object
- RubyJard::KeyBindings
- Defined in:
- lib/ruby_jard/key_bindings.rb
Overview
Register custom key bindings and corresponding action, try to match a key binding sequence from input. As this class is performant-sensitive, a lookup tree is built and updated whenever a new key is added.
Instance Attribute Summary collapse
-
#indexes ⇒ Object
readonly
Returns the value of attribute indexes.
Instance Method Summary collapse
-
#initialize ⇒ KeyBindings
constructor
A new instance of KeyBindings.
- #match(&read_key) ⇒ Object
- #push(sequence, action) ⇒ Object
- #to_a ⇒ Object
Constructor Details
#initialize ⇒ KeyBindings
Returns a new instance of KeyBindings.
12 13 14 15 |
# File 'lib/ruby_jard/key_bindings.rb', line 12 def initialize @key_bindings = [] @indexes = {} end |
Instance Attribute Details
#indexes ⇒ Object (readonly)
Returns the value of attribute indexes.
10 11 12 |
# File 'lib/ruby_jard/key_bindings.rb', line 10 def indexes @indexes end |
Instance Method Details
#match(&read_key) ⇒ Object
34 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 62 63 64 65 66 |
# File 'lib/ruby_jard/key_bindings.rb', line 34 def match(&read_key) raise RubyJard::Error, 'This method requires a block' unless block_given? buffer = '' node = @indexes loop do keys = read_key.call if keys.nil? # No more key. Match the current node if node[nil].nil? return buffer else return node[nil] end end buffer += keys keys.bytes.each do |byte| if node[byte].is_a?(Hash) # Not sure, continue to match node = node[byte] elsif node[byte].nil? # It's sure that no more bindings to match return buffer elsif buffer == node[byte].sequence # Exact match current key binding return node[byte] else return buffer end end end end |
#push(sequence, action) ⇒ Object
21 22 23 24 25 26 27 28 29 30 31 32 |
# File 'lib/ruby_jard/key_bindings.rb', line 21 def push(sequence, action) if sequence.is_a?(Array) sequence.each { |s| push(s, action) } return end raise RubyJard::Error if sequence.to_s.empty? key_binding = RubyJard::KeyBinding.new(sequence, action) reindex(key_binding) @key_bindings << key_binding end |
#to_a ⇒ Object
17 18 19 |
# File 'lib/ruby_jard/key_bindings.rb', line 17 def to_a @key_bindings.dup end |