Module: PhraseApp::InContextEditor::HashFlattener
- Defined in:
- lib/phraseapp-in-context-editor-ruby/hash_flattener.rb
Constant Summary collapse
- FLATTEN_SEPARATOR =
"."
- SEPARATOR_ESCAPE_CHAR =
"\001"
Class Method Summary collapse
- .contains_only_dots?(string) ⇒ Boolean
- .ends_with_dot?(string) ⇒ Boolean
- .escape_default_separator(key) ⇒ Object
- .expand_flat_hash(flat_hash, prefix = nil) ⇒ Object
- .flatten(hash, escape, previous_key = nil, &block) ⇒ Object
- .starts_with_dot?(string) ⇒ Boolean
- .to_nested_hash(key, value) ⇒ Object
Class Method Details
.contains_only_dots?(string) ⇒ Boolean
36 37 38 |
# File 'lib/phraseapp-in-context-editor-ruby/hash_flattener.rb', line 36 def self.contains_only_dots?(string) string.to_s.gsub(/\./, "").length == 0 end |
.ends_with_dot?(string) ⇒ Boolean
44 45 46 |
# File 'lib/phraseapp-in-context-editor-ruby/hash_flattener.rb', line 44 def self.ends_with_dot?(string) string.to_s.end_with?(".") end |
.escape_default_separator(key) ⇒ Object
48 49 50 |
# File 'lib/phraseapp-in-context-editor-ruby/hash_flattener.rb', line 48 def self.escape_default_separator(key) key.to_s.tr(FLATTEN_SEPARATOR, SEPARATOR_ESCAPE_CHAR) end |
.expand_flat_hash(flat_hash, prefix = nil) ⇒ Object
17 18 19 20 21 22 23 24 25 26 |
# File 'lib/phraseapp-in-context-editor-ruby/hash_flattener.rb', line 17 def self.(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, &block) ⇒ Object
8 9 10 11 12 13 14 15 |
# File 'lib/phraseapp-in-context-editor-ruby/hash_flattener.rb', line 8 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) ⇒ Boolean
40 41 42 |
# File 'lib/phraseapp-in-context-editor-ruby/hash_flattener.rb', line 40 def self.starts_with_dot?(string) string.to_s.start_with?(".") end |
.to_nested_hash(key, value) ⇒ Object
28 29 30 31 32 33 34 |
# File 'lib/phraseapp-in-context-editor-ruby/hash_flattener.rb', line 28 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 |