Module: Mobility::Plugins::Default

Extended by:
Mobility::Plugin
Defined in:
lib/mobility/plugins/default.rb

Overview

Defines value or proc to fall through to if return value from getter would otherwise be nil. This plugin is disabled by default but will be enabled if any value is passed as the default option key.

If default is a Proc, it will be called with the context of the model, and passed arguments:

  • the attribute name (a String)

  • the locale (a Symbol)

  • hash of options passed in to accessor

The proc can accept zero to three arguments (see examples below)

Examples:

With default enabled (falls through to default value)

class Post
  extend Mobility
  translates :title, default: 'foo'
end

Mobility.locale = :en
post = Post.new(title: "English title")

Mobility.locale = :de
post.title
#=> 'foo'

Overriding default with reader option

class Post
  extend Mobility
  translates :title, default: 'foo'
end

Mobility.locale = :en
post  = Post.new(title: "English title")

Mobility.locale = :de
post.title
#=> 'foo'

post.title(default: 'bar')
#=> 'bar'

post.title(default: nil)
#=> nil

Using Proc as default

class Post
  extend Mobility
  translates :title, default: lambda { |attribute, locale| "#{attribute} in #{locale}" }
end

Mobility.locale = :en
post = Post.new(title: nil)
post.title
#=> "title in en"

post.title(default: lambda { self.class.name.to_s })
#=> "Post"

Defined Under Namespace

Modules: BackendMethods

Class Method Summary collapse

Methods included from Mobility::Plugin

configure, configure_default, default, dependencies, dependencies_satisfied?, included, included_hook, initialize_hook, requires

Class Method Details

.[](default_value, locale:, accessor_options:, model:, attribute:) ⇒ Object

Generate a default value for given parameters.

Parameters:

  • default_value (Object, Proc)

    A default value or Proc

  • locale (Symbol)
  • accessor_options (Hash)
  • attribute (String)

79
80
81
82
83
84
# File 'lib/mobility/plugins/default.rb', line 79

def self.[](default_value, locale:, accessor_options:, model:, attribute:)
  return default_value unless default_value.is_a?(Proc)
  args = [attribute, locale, accessor_options]
  args = args.first(default_value.arity) unless default_value.arity < 0
  model.instance_exec(*args, &default_value)
end