Module: R18n::Utils

Defined in:
lib/r18n-core/utils.rb

Constant Summary collapse

HTML_ENTRIES =
{ '&' => '&amp;', '<' => '&lt;', '>' => '&gt;' }

Class Method Summary collapse

Class Method Details

.deep_merge!(a, b) ⇒ Object

Recursively hash merge.



57
58
59
60
61
62
63
64
65
66
67
# File 'lib/r18n-core/utils.rb', line 57

def self.deep_merge!(a, b)
  b.each_pair do |key, value|
    another = a[key]
    a[key] = if another.is_a?(Hash) && value.is_a?(Hash)
      deep_merge!(another, value)
    else
      value
    end
  end
  a
end

.escape_html(content) ⇒ Object

Escape HTML entries (<, >, &). Copy from HAML helper.



37
38
39
40
41
42
43
# File 'lib/r18n-core/utils.rb', line 37

def self.escape_html(content)
  if defined? ActiveSupport::SafeBuffer
    ActiveSupport::SafeBuffer.new + content
  else
    content.to_s.gsub(/[><&]/) { |s| HTML_ENTRIES[s] }
  end
end

.hash_map(hash, &block) ⇒ Object

Invokes block once for each key and value of hash. Creates a new hash with the keys and values returned by the block.



47
48
49
50
51
52
53
54
# File 'lib/r18n-core/utils.rb', line 47

def self.hash_map(hash, &block)
  result = {}
  hash.each_pair do |key, val|
    new_key, new_value = block.call(key, val)
    result[new_key] = new_value
  end
 result
end

.to_date(time) ⇒ Object

Convert Time to Date. Backport from Ruby 1.9.



25
26
27
28
29
30
31
32
# File 'lib/r18n-core/utils.rb', line 25

def self.to_date(time)
  if '1.8.' == RUBY_VERSION[0..3]
    d = Date.send(:civil_to_jd, time.year, time.mon, time.mday, Date::ITALY)
    Date.new!(Date.send(:jd_to_ajd, d, 0, 0), 0, Date::ITALY)
  else
    time.to_date
  end
end

.use_syck(&block) ⇒ Object

Call block with Syck yamler. It used to load RedCloth, which isn’t support Psych.



71
72
73
74
75
76
77
78
79
80
81
82
83
# File 'lib/r18n-core/utils.rb', line 71

def self.use_syck(&block)
  if RUBY_PLATFORM == 'java' && defined?(YAML::ENGINE)
    YAML::ENGINE.yamler = 'psych'
    yield
  elsif '1.8.' == RUBY_VERSION[0..3]
    yield
  else
    origin_yamler = YAML::ENGINE.yamler
    YAML::ENGINE.yamler = 'syck'
    yield
    YAML::ENGINE.yamler = origin_yamler
  end
end