Class: I18nScrewdriver::Translation

Inherits:
String
  • Object
show all
Defined in:
lib/i18n_screwdriver/translation.rb

Constant Summary collapse

Error =
Class.new(StandardError)

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#optionsObject

Returns the value of attribute options.



5
6
7
# File 'lib/i18n_screwdriver/translation.rb', line 5

def options
  @options
end

#textObject

Returns the value of attribute text.



5
6
7
# File 'lib/i18n_screwdriver/translation.rb', line 5

def text
  @text
end

Class Method Details

.application_frames(backtrace) ⇒ Object



27
28
29
# File 'lib/i18n_screwdriver/translation.rb', line 27

def self.application_frames(backtrace)
  backtrace.select{ |path| path.starts_with?(::Rails.root.to_s) }
end

.emit_warning(message) ⇒ Object

Raises:



22
23
24
25
# File 'lib/i18n_screwdriver/translation.rb', line 22

def self.emit_warning(message)
  raise Error, message unless ::Rails.env.production?
  ::Rails.logger.warn(%|I18nScrewdriver: #{message}\n#{application_frames(caller).join("\n")}|)
end

.new(text, **options, &block) ⇒ Object



7
8
9
10
11
12
13
14
15
16
17
18
19
20
# File 'lib/i18n_screwdriver/translation.rb', line 7

def self.new(text, **options, &block)
  translation = super(options[:raw] ? text : I18nScrewdriver.translate(text, **options))
  translation.text = text
  translation.options = options

  if block
    urls = Array(block.call)
    urls_to_interpolate_count = translation.scan(/<<.+?>>/).count
    emit_warning("invalid number of urls specified (#{urls.count} <> #{urls_to_interpolate_count})") unless urls.count == urls_to_interpolate_count
    translation.linkify(block.binding, urls)
  end

  translation
end

Instance Method Details

#linkify(binding, urls) ⇒ Object



31
32
33
34
35
36
37
38
39
40
# File 'lib/i18n_screwdriver/translation.rb', line 31

def linkify(binding, urls)
  context = binding ? eval('self', binding) : self
  keep_html_safety do
    gsub!(/<<.+?>>/).each_with_index do |text, index|
      context.instance_eval do
        link_to(text[2..-3], *urls[index])
      end
    end
  end
end