Class: I18nAccessors::Missing

Inherits:
Module
  • Object
show all
Defined in:
lib/i18n_accessors/missing.rb

Overview

Defines method_missing and respond_to_missing? methods for a set of attributes such that a method call using a locale accessor, like:

article.title_pt_br

will return the value of article.title with the locale set to pt-BR around the method call.

Examples:

Using missing on a plain old ruby class

class Post
  def title
    "title in #{I18n.locale}"
  end
  include I18nAccessors::Missing.new("title")
end

I18n.locale = :en
post = Post.new
post.title
#=> "title in en"
post.title_fr
#=> "title in fr"

Instance Method Summary collapse

Constructor Details

#initialize(*attributes) ⇒ Missing

Returns a new instance of Missing.

Parameters:

  • One (String)

    or more attributes



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/i18n_accessors/missing.rb', line 30

def initialize(*attributes)
  method_name_regex = /\A(#{attributes.join('|'.freeze)})_([a-z]{2}(_[a-z]{2})?)(=?|\??)\z/.freeze

  define_method :method_missing do |method_name, *arguments, &block|
    if method_name =~ method_name_regex
      attribute = $1.to_sym
      locale, suffix = $2.split('_'.freeze)
      locale = "#{locale}-#{suffix.upcase}".freeze if suffix
      I18nAccessors.i18n_class.with_locale(locale.to_sym) { public_send("#{attribute}#{$4}".freeze, *arguments) }
    else
      super(method_name, *arguments, &block)
    end
  end

  define_method :respond_to_missing? do |method_name, include_private = false|
    (method_name =~ method_name_regex) || super(method_name, include_private)
  end
end