module PhraseApp::InContextEditor::HashFlattener
Constants
- FLATTEN_SEPARATOR
- SEPARATOR_ESCAPE_CHAR
Public Class Methods
contains_only_dots?(string)
click to toggle source
# File lib/phraseapp-in-context-editor-ruby/hash_flattener.rb, line 35 def self.contains_only_dots?(string) string.to_s.gsub(/\./, "").length == 0 end
ends_with_dot?(string)
click to toggle source
# File lib/phraseapp-in-context-editor-ruby/hash_flattener.rb, line 43 def self.ends_with_dot?(string) string.to_s.end_with?(".") end
escape_default_separator(key)
click to toggle source
# File lib/phraseapp-in-context-editor-ruby/hash_flattener.rb, line 47 def self.escape_default_separator(key) key.to_s.tr(FLATTEN_SEPARATOR, SEPARATOR_ESCAPE_CHAR) end
expand_flat_hash(flat_hash, prefix=nil)
click to toggle source
# File lib/phraseapp-in-context-editor-ruby/hash_flattener.rb, line 16 def self.expand_flat_hash(flat_hash, prefix=nil) flat_hash ||= [] result = flat_hash.map do |key, value| key = key.gsub(/#{prefix}[\.]?/, '') if prefix to_nested_hash(key, value) end result = result.inject({}) { |hash, subhash| hash.deep_merge!(subhash) } result end
flatten(hash, escape, previous_key=nil) { |current_key, value| ... }
click to toggle source
# File lib/phraseapp-in-context-editor-ruby/hash_flattener.rb, line 7 def self.flatten(hash, escape, previous_key=nil, &block) hash.each_pair do |key, value| key = escape_default_separator(key) if escape current_key = [previous_key, key].compact.join(FLATTEN_SEPARATOR).to_sym yield current_key, value flatten(value, escape, current_key, &block) if value.is_a?(Hash) end end
starts_with_dot?(string)
click to toggle source
# File lib/phraseapp-in-context-editor-ruby/hash_flattener.rb, line 39 def self.starts_with_dot?(string) string.to_s.start_with?(".") end
to_nested_hash(key, value)
click to toggle source
# File lib/phraseapp-in-context-editor-ruby/hash_flattener.rb, line 27 def self.to_nested_hash key, value if contains_only_dots?(key) or starts_with_dot?(key) or ends_with_dot?(key) {key.to_sym => value} else key.to_s.split(".").reverse.inject(value) { |hash, part| {part.to_sym => hash} } end end