Module: AttributePredicates::Extensions::Module

Defined in:
lib/attribute_predicates/extensions/module.rb

Overview

Adds support for automatically defining predicate methods using attr_predicate when defining attributes using attr, attr_reader, attr_reader, and attr_accessor.

Examples

The predicate methods for attributes checks whether the value is blank? for determining whether true or false should be returned. For example,

class Person
  attr_accessor :value
end

p = Person.new
p.value = false
p.value?    # => false

p.value = true
p.value?    # => true

p.value = []
p.value?    # => false

p.value = [false]
p.value?    # => true

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(base) ⇒ Object

:nodoc:



29
30
31
32
33
34
35
36
# File 'lib/attribute_predicates/extensions/module.rb', line 29

def self.included(base) #:nodoc:
  base.class_eval do
    %w(attr attr_reader attr_writer attr_accessor).each do |method|
      alias_method "#{method}_without_predicates", method
      alias_method method, "#{method}_with_predicates"
    end
  end
end

Instance Method Details

#attr_with_predicates(*args) ⇒ Object

Defines a predicate method, using attr_predicate, in addition to the attribute accessors. For example,

module Mod
  attr :is_okay
end

Mod.instance-methods.sort # => ["is_okay", "is_okay?"]


46
47
48
49
# File 'lib/attribute_predicates/extensions/module.rb', line 46

def attr_with_predicates(*args)
  attr_without_predicates(*args)
  attr_predicate(args.first)
end