class Tr8n::LanguageCase

Constants

TR8N_HTML_TAGS_REGEX

Public Class Methods

new(attrs = {}) click to toggle source
Calls superclass method Tr8n::Base::new
# File lib/tr8n/language_case.rb, line 40
def initialize(attrs = {})
  super
  self.attributes[:rules] = []
  if hash_value(attrs, :rules)
    self.attributes[:rules] = hash_value(attrs, :rules).collect{ |rule| Tr8n::LanguageCaseRule.new(rule.merge(:language_case => self)) }
  end
end

Public Instance Methods

apply(value, object = nil, options = {}) click to toggle source

Evaluation Methods

# File lib/tr8n/language_case.rb, line 59
def apply(value, object = nil, options = {})
  value = value.to_s

  decorator = Tr8n::Decorators::Base.decorator

  options = options.merge(:skip_decorations => true) if value.index('not_translated')

  html_tokens = value.scan(TR8N_HTML_TAGS_REGEX).uniq
  sanitized_value = value.gsub(TR8N_HTML_TAGS_REGEX, '')

  if application.to_s == 'phrase'
    words = [sanitized_value]
  else
    words = sanitized_value.split(/[\s\/\\]/).uniq
  end

  # replace html tokens with temporary placeholders {$h1}
  html_tokens.each_with_index do |html_token, index|
    value = value.gsub(html_token, "{$h#{index}}")
  end

  # replace words with temporary placeholders {$w1}
  words.each_with_index do |word, index|
    value = value.gsub(word, "{$w#{index}}")
  end

  transformed_words = []
  words.each do |word|
    case_rule = find_matching_rule(word, object)
    case_value = case_rule ? case_rule.apply(word) : word
    transformed_words << decorator.decorate_language_case(self, case_rule, word, case_value, options)
  end

  # replace back the temporary placeholders with the html tokens
  transformed_words.each_with_index do |word, index|
    value = value.gsub("{$w#{index}}", word)
  end

  # replace back the temporary placeholders with the html tokens
  html_tokens.each_with_index do |html_token, index|
    value = value.gsub("{$h#{index}}", html_token)
  end

  value
end
find_matching_rule(value, object = nil) click to toggle source
# File lib/tr8n/language_case.rb, line 48
def find_matching_rule(value, object = nil)
  rules.each do |rule|
    return rule if rule.evaluate(value, object)
  end
  nil
end