Class: Mobility::Plugins::Default

Inherits:
Module
  • Object
show all
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.

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 { |model:, attribute:| attribute.to_s }
end

post = Post.new(title: nil)
post.title
#=> "title"

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

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(default_option) ⇒ Default

Returns a new instance of Default.



61
62
63
64
65
66
67
68
69
70
# File 'lib/mobility/plugins/default.rb', line 61

def initialize(default_option)
  define_method :read do |locale, options = {}|
    default = options.has_key?(:default) ? options.delete(:default) : default_option
    if (value = super(locale, options)).nil?
      default.is_a?(Proc) ? default.call(model: model, attribute: attribute) : default
    else
      value
    end
  end
end

Class Method Details

.apply(attributes, option) ⇒ Object

Applies default plugin to attributes.

Parameters:



57
58
59
# File 'lib/mobility/plugins/default.rb', line 57

def self.apply(attributes, option)
  attributes.backend_class.include(new(option))
end