Method: Mobility::Attributes#initialize

Defined in:
lib/mobility/attributes.rb

#initialize(method, *_attributes, **_options) ⇒ Attributes

Returns a new instance of Attributes.

Parameters:

  • method (Symbol)

    One of: [reader, writer, accessor]

  • _attributes (Array<String>)

    Attributes to define backend for

  • _options (Hash)

    Backend options hash

Options Hash (**_options):

  • model_class (Class)

    Class of model

  • locale_accessors (Boolean, Array<Symbol>)

    Enable locale accessors or specify locales for which accessors should be defined on this model backend. Will default to true if dirty option is true.

  • cache (Boolean) — default: true

    Enable cache for this model backend

  • fallbacks (Boolean, Hash)

    Enable fallbacks or specify fallbacks for this model backend

  • dirty (Boolean)

    Enable dirty tracking for this model backend

Raises:

  • (ArgumentError)

    if method is not reader, writer or accessor


125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
# File 'lib/mobility/attributes.rb', line 125

def initialize(method, *_attributes, **_options)
  raise ArgumentError, "method must be one of: reader, writer, accessor" unless %i[reader writer accessor].include?(method)
  @options = _options
  @attributes = _attributes.map &:to_s
  model_class = options[:model_class]
  @backend_name = options.delete(:backend) || Mobility.config.default_backend
  @backend_class = Class.new(get_backend_class(backend:     @backend_name,
                                               model_class: model_class))

  options[:locale_accessors] ||= true if options[:dirty]

  @backend_class.configure!(options) if @backend_class.respond_to?(:configure!)

  @backend_class.include Backend::Cache unless options[:cache] == false
  @backend_class.include Backend::Dirty.for(model_class) if options[:dirty]
  @backend_class.include Backend::Fallbacks if options[:fallbacks]
  @accessor_locales = options[:locale_accessors]
  @accessor_locales = Mobility.config.default_accessor_locales if options[:locale_accessors] == true

  attributes.each do |attribute|
    define_backend(attribute)

    if %i[accessor reader].include?(method)
      define_method attribute do |**options|
        mobility_get(attribute, options)
      end

      define_method "#{attribute}?" do |**options|
        mobility_present?(attribute, options)
      end
    end

    define_method "#{attribute}=" do |value|
      mobility_set(attribute, value)
    end if %i[accessor writer].include?(method)

    define_locale_accessors(attribute, @accessor_locales) if @accessor_locales
  end
end