Class: Module

Inherits:
Object
  • Object
show all
Defined in:
lib/everythingrb/core/module.rb

Instance Method Summary collapse

Instance Method Details

#attr_predicate(*attributes) ⇒ nil

Creates predicate (boolean) methods that return true/false Similar to attr_reader, attr_writer, etc. Designed to work with regular classes, Struct, and Data objects.

Note: If ActiveSupport is loaded, this will check if the value is present? instead of truthy

Examples:

With a regular class

class User
  attr_predicate :admin
  attr_accessor :admin
end

user = User.new
user.admin? # => false
user.admin = true
user.admin? # => true

With Struct/Data

Person = Struct.new(:active)
Person.attr_predicate(:active)

person = Person.new(active: true)
person.active? # => true

Parameters:

  • *attributes (Array<Symbol, String>)

    Attribute names

Returns:

  • (nil)

Raises:

  • (ArgumentError)

    If a predicate method of the same name already exists



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/everythingrb/core/module.rb', line 35

def attr_predicate(*attributes)
  attributes.each do |attribute|
    if method_defined?(:"#{attribute}?")
      raise ArgumentError, "Cannot create predicate method on #{self.class} - #{attribute}? is already defined. Please choose a different name or remove the existing method."
    end

    module_eval <<-RUBY, __FILE__, __LINE__ + 1
      def #{attribute}?
        value =
          if instance_variable_defined?(:@#{attribute})
            @#{attribute}
          elsif respond_to?(:#{attribute})
            self.#{attribute}
          end

        return false if value.nil?

        defined?(ActiveSupport) ? !!value.presence : !!value
      end
    RUBY
  end

  nil
end