Module: Mobility::Translates

Defined in:
lib/mobility/translates.rb

Overview

Defines methods for attaching backends to a class. A block can optionally be passed to accessors to configure backend (see example below).

Examples:

Defining backend on a class

class MyClass
  extend Translates
  mobility_accessor :foo, option: :value
end

Passing backend to a block

class MyClass
  extend Translates
  mobility_accessor :foo, option: :value do
    # add custom code to backend class for this attribute only
  end
end

Defining only a backend reader and presence method

class MyClass
  extend Translates
  mobility_reader :foo
end

instance = MyClass.new
instance.foo         #=> (some value)
instance.foo?        #=> true
instance.foo = "foo" #=> NoMethodError

Defining only a backend writer

class MyClass
  extend Translates
  mobility_writer :foo
end

instance = MyClass.new
instance.foo         #=> NoMethodError
instance.foo?        #=> NoMethodError
instance.foo = "foo" #=> (sets attribute to value "foo")

Instance Method Summary collapse

Instance Method Details

#mobility_accessor(*attributes, **options) { ... } ⇒ Object

Defines mobility accessor on model class.

Parameters:

  • attributes (Array<String>)
  • options (Hash)

Yields:

  • Yields to block with backend as context



# File 'lib/mobility/translates.rb', line 44

#mobility_reader(*attributes, **options) { ... } ⇒ Object

Defines mobility reader and presence method on model class.

Parameters:

  • attributes (Array<String>)
  • options (Hash)

Yields:

  • Yields to block with backend as context



# File 'lib/mobility/translates.rb', line 50

#mobility_writer(*attributes, **options) { ... } ⇒ Object

Defines mobility writer on model class.

Parameters:

  • attributes (Array<String>)
  • options (Hash)

Yields:

  • Yields to block with backend as context



61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/mobility/translates.rb', line 61

%w[accessor reader writer].each do |method|
  class_eval <<-EOM, __FILE__, __LINE__ + 1
    def mobility_#{method}(*args, **options, &block)
      attributes = Attributes.new(:#{method}, *args, options.merge(model_class: self))
      attributes.backend.instance_eval &block if block_given?
      attributes.each do |attribute|
        alias_method "\#{attribute}_before_mobility",  attribute        if method_defined?(attribute)        && #{%w[accessor reader].include? method}
        alias_method "\#{attribute}_before_mobility=", "\#{attribute}=" if method_defined?("\#{attribute}=") && #{%w[accessor writer].include? method}
       end
      include attributes
    end
  EOM
end