Class: Mobility::Plugins::FallthroughAccessors

Inherits:
Module
  • Object
show all
Defined in:
lib/mobility/plugins/fallthrough_accessors.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. The class is called “FallthroughAccessors” because when included in a model class, locale-specific methods will be available even if not explicitly defined with the locale_accessors option.

This is a less efficient (but more open-ended) implementation of locale accessors, for use in cases where the locales to be used are not known when the model class is generated.

Examples:

Using fallthrough locales on a plain old ruby class

class Post
  def title
    "title in #{Mobility.locale}"
  end
  include Mobility::FallthroughAccessors.new("title")
end

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

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(*attributes) ⇒ FallthroughAccessors

Returns a new instance of FallthroughAccessors.

Parameters:

  • One (String)

    or more attributes


46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/mobility/plugins/fallthrough_accessors.rb', line 46

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

  define_method :method_missing do |method_name, *args, &block|
    if method_name =~ method_name_regex
      attribute_method = "#{$1}#{$4}"
      locale, suffix = $2.split('_')
      locale = "#{locale}-#{suffix.upcase}" if suffix
      if $4 == '=' # writer
        public_send(attribute_method, args[0], **(args[1] || {}), locale: locale.to_sym)
      else         # reader
        public_send(attribute_method, **(args[0] || {}), locale: locale.to_sym)
      end
    else
      super(method_name, *args, &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

Class Method Details

.apply(attributes, option) ⇒ Object

Apply fallthrough accessors plugin to attributes.

Parameters:


41
42
43
# File 'lib/mobility/plugins/fallthrough_accessors.rb', line 41

def self.apply(attributes, option)
  attributes.model_class.include new(*attributes.names) if option
end