Module: PlainRecord::Extra::I18n

Defined in:
lib/plain_record/extra/i18n.rb

Overview

Extention to get field value depend on user locale.

You can’t use this filter for texts, because you need to set hash of language code to translated string. For example in YAML fiels:

title:

en: Title
ru: Заголовок

Then just set filter to ‘virtual` or `field`.

class Post
  include PlainRecord::Resource
  include PlainRecord::Extra::I18n

  field :title, i18n
end

By default, this filter will use current locale from Rails I18n or R18n, if they are defined. If you need to take locale from another space, just redefine ‘locale` model method.

class Post
  def locale
    ENV['locale']
  end
end

Defined Under Namespace

Modules: Model

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(base) ⇒ Object



50
51
52
# File 'lib/plain_record/extra/i18n.rb', line 50

def self.included(base)
  base.send :extend, Model
end

Instance Method Details

#get_translation(name, hash, *params) ⇒ Object

Return subvalue of ‘hash` depend on user locale from `locale` method.

If R18n or Rails I18n is loaded it will use them logic to translate.



81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
# File 'lib/plain_record/extra/i18n.rb', line 81

def get_translation(name, hash, *params)
  return hash unless hash.is_a? Hash
  path = "#{self.class.name}##{name}"

  if defined? R18n::I18n and locale.is_a? R18n::I18n
    r18n = locale
    r18n.locales.each do |lang|
      code = lang.code
      next unless hash.has_key? code

      result = hash[code]
      type   = self.class.fields_i18n_types[name.to_sym]

      if type
        return r18n.filter_list.
          process(:all, type, result, lang, path, params)
      elsif result.is_a? String
        result = ::R18n::TranslatedString.new(result, lang, path)
        return r18n.filter_list.process_string(:all, result, path, params)
      else
        return result
      end
    end

    ::R18n::Untranslated.new("#{self.class.name}#", name,
                             locale.locale, locale.filter_list)

  elsif defined? ::I18n
    hash[locale.to_s]

  else
    hash[locale]
  end
end

#localeObject

Return default locale. By default it look in R18n or Rails I18n. Redefine it if you need another logic.



56
57
58
59
60
61
62
63
64
# File 'lib/plain_record/extra/i18n.rb', line 56

def locale
  if defined? ::R18n::I18n
    ::R18n.get
  elsif defined? ::I18n
    ::I18n.locale
  else
    raise "Can't find R18n or I18n. Redefine `locale` method."
  end
end

#locale_codeObject

Return locale code depend on autodetected I18n library.



67
68
69
70
71
72
73
74
75
76
# File 'lib/plain_record/extra/i18n.rb', line 67

def locale_code
  code = locale
  if defined? R18n::I18n and code.is_a? R18n::I18n
    code.locale.code
  elsif code.is_a? Symbol
    code.to_s
  else
    code
  end
end