Class: Module

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

Overview

Extensions to Ruby’s core Module class

Provides:

  • #attr_predicate: Create boolean-style accessor methods

Examples:

require "everythingrb/module"

class User
  attr_accessor :admin
  attr_predicate :admin
end

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

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

Raises:

  • (ArgumentError)

    If a predicate method of the same name already exists



53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
# File 'lib/everythingrb/module.rb', line 53

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 "      def \#{attribute}?\n        value =\n          if instance_variable_defined?(:@\#{attribute})\n            @\#{attribute}\n          elsif respond_to?(:\#{attribute})\n            self.\#{attribute}\n          end\n\n        return false if value.nil?\n\n        defined?(ActiveSupport) ? !!value.presence : !!value\n      end\n    RUBY\n  end\n\n  nil\nend\n", __FILE__, __LINE__ + 1