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

Parameters:

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

Yields:

  • Yields to block with backend as context


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

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

Parameters:

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

Yields:

  • Yields to block with backend as context


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

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

Parameters:

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

Yields:

  • Yields to block with backend as context


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

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