Sha256: f6d88ffb6fea679492b6a6746e5590d61ab2b22c3d838196a4c4fbf80652e65b

Contents?: true

Size: 1.26 KB

Versions: 7

Compression:

Stored size: 1.26 KB

Contents

module I18nScrewdriver
  class Translation < String
    attr_accessor :text, :options

    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
        raise ArgumentError, "too few urls specified" if urls.count < urls_to_interpolate_count
        if urls.count > urls_to_interpolate_count
          raise ArgumentError, "too many urls specified (#{urls.count} <> #{urls_to_interpolate_count})" unless urls.last.is_a?(Hash)
          translation = new(translation % urls.last, :raw => true)
        end
        translation.linkify(block.binding, urls)
      end

      translation
    end

    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

    private

    def keep_html_safety
      html_safe = @html_safe
      yield
      @html_safe = html_safe
      self
    end
  end
end

Version data entries

7 entries across 7 versions & 1 rubygems

Version Path
i18n_screwdriver-8.0 lib/i18n_screwdriver/translation.rb
i18n_screwdriver-7.5 lib/i18n_screwdriver/translation.rb
i18n_screwdriver-7.4 lib/i18n_screwdriver/translation.rb
i18n_screwdriver-7.3 lib/i18n_screwdriver/translation.rb
i18n_screwdriver-7.2 lib/i18n_screwdriver/translation.rb
i18n_screwdriver-7.1 lib/i18n_screwdriver/translation.rb
i18n_screwdriver-7.0 lib/i18n_screwdriver/translation.rb