Module: Aspect::HasAttributes

Included in:
Verifier
Defined in:
lib/aspect/has_attributes.rb

Overview

Easily define attribute getter/setter/accessors on an object with a ‘.attribute` class method.

This also defines the ‘#update_attributes` instance method to use for mass assignment.

**Documentation Notes**

Since ‘.attribute` is a method which dynamically defines methods, you may need to use a special declaration in order to associate the documentation to the method.

Here’s how I do it with [YARD](yardoc.org):

“‘rb class User

include Aspect::HasAttributes

# @method name
# Get the name.
#
# @return [String]

# @method name=
# Set the name.
#
# @param [#to_s] value
# @return [String]
attribute(:name) { |value| value.to_s.strip }

# @method admin?
# Get whether this user is an admin.
#
# @return [Boolean]

# @method admin=
# Set whether this user is an admin.
#
# @param [Boolean] value
# @return [Boolean]
attribute(:admin, query: true)

end “‘

Defined Under Namespace

Modules: ClassMethods

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(base) ⇒ Object

On include hook to extend ‘ClassMethods`.



185
186
187
# File 'lib/aspect/has_attributes.rb', line 185

def included(base)
  base.send(:extend, ClassMethods)
end

Instance Method Details

#update_attributes(attributes = {}) ⇒ Object

Update attributes on this object.

Examples:

class User
  include Aspect::HasAttributes

  attribute(:name) { |value| value.to_s.strip }
  attribute(:moderator, query: true)
  attribute(:admin, query: true) { |value| @moderator ? value : false }
end

user = User.new

user.name # => nil
user.moderator? # => false
user.admin? # => false

user.update_attributes(name: "  Ezio Auditore  ", moderator: true)

user.name # => "Ezio Auditore"
user.moderator? # => true
user.admin? # => false

In ‘#initialize`

class User
  include Aspect::HasAttributes

  def initialize(attributes={})
    update_attributes(attributes)
  end

  attribute(:name) { |value| value.to_s.strip }
  attribute(:moderator, query: true)
  attribute(:admin, query: true) { |value| @moderator ? value : false }
end

user = User.new(name: "  Ezio Auditore  ", moderator: true)

user.name # => "Ezio Auditore"
user.moderator? # => true
user.admin? # => false

Parameters:

  • attributes (Hash, #to_h) (defaults to: {})

Returns:

  • (Object)


232
233
234
235
236
# File 'lib/aspect/has_attributes.rb', line 232

def update_attributes(attributes={})
  attributes.to_h.each { |name, value| send("#{name}=", value) }

  self
end