Module: I18n::JS::Utils

Defined in:
lib/i18n/js/utils.rb

Constant Summary collapse

MERGER =

deep_merge by Stefan Rusterholz, see <www.ruby-forum.com/topic/142809>. The last result is modified to treat ‘nil` as missing key

proc do |_key, v1, v2|
  Hash === v1 && Hash === v2 ? v1.merge(v2, &MERGER) : (v2.nil? ? v1 : v2)
end
HASH_NIL_VALUE_CLEANER_PROC =
proc do |k, v|
  v.kind_of?(Hash) ? (v.delete_if(&HASH_NIL_VALUE_CLEANER_PROC); false) : v.nil?
end

Class Method Summary collapse

Class Method Details

.deep_key_sort(hash) ⇒ Object



42
43
44
45
46
47
48
49
# File 'lib/i18n/js/utils.rb', line 42

def self.deep_key_sort(hash)
  # Avoid things like `true` or `1` from YAML which causes error
  hash.keys.sort {|a, b| a.to_s <=> b.to_s}.
    each_with_object({}) do |key, seed|
    value = hash[key]
    seed[key] = value.is_a?(Hash) ? deep_key_sort(value) : value
  end
end

.deep_merge(target_hash, hash) ⇒ Object

:nodoc:



18
19
20
# File 'lib/i18n/js/utils.rb', line 18

def self.deep_merge(target_hash, hash) # :nodoc:
  target_hash.merge(hash, &MERGER)
end

.deep_merge!(target_hash, hash) ⇒ Object

:nodoc:



22
23
24
# File 'lib/i18n/js/utils.rb', line 22

def self.deep_merge!(target_hash, hash) # :nodoc:
  target_hash.merge!(hash, &MERGER)
end

.deep_reject(hash, scopes = [], &block) ⇒ Object



26
27
28
29
30
31
32
# File 'lib/i18n/js/utils.rb', line 26

def self.deep_reject(hash, scopes = [], &block)
  hash.each_with_object({}) do |(k, v), memo|
    unless block.call(k, v, scopes + [k.to_s])
      memo[k] = v.kind_of?(Hash) ? deep_reject(v, scopes + [k.to_s], &block) : v
    end
  end
end

.scopes_match?(scopes1, scopes2) ⇒ Boolean

Returns:

  • (Boolean)


34
35
36
37
38
39
40
# File 'lib/i18n/js/utils.rb', line 34

def self.scopes_match?(scopes1, scopes2)
  if scopes1.length == scopes2.length
    [scopes1, scopes2].transpose.all? do |scope1, scope2|
      scope1.to_s == '*' || scope2.to_s == '*' || scope1.to_s == scope2.to_s
    end
  end
end

.strip_keys_with_nil_values(hash) ⇒ Object



14
15
16
# File 'lib/i18n/js/utils.rb', line 14

def self.strip_keys_with_nil_values(hash)
  hash.dup.delete_if(&HASH_NIL_VALUE_CLEANER_PROC)
end