Module: Virtus::ClassMethods

Defined in:
lib/virtus/class_methods.rb

Overview

Class methods that are added when you include Virtus

Constant Summary collapse

WRITER_METHOD_REGEXP =
/=\z/.freeze
INVALID_WRITER_METHODS =
%w[ == != === []= attributes= ].to_set.freeze

Instance Method Summary collapse

Instance Method Details

#allowed_writer_methodsSet

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

The list of writer methods that can be mass-assigned to in #attributes=

Returns:

  • (Set)


88
89
90
91
92
93
94
95
96
# File 'lib/virtus/class_methods.rb', line 88

def allowed_writer_methods
  @allowed_writer_methods ||=
    begin
      allowed_writer_methods  = public_instance_methods.map(&:to_s)
      allowed_writer_methods  = allowed_writer_methods.grep(WRITER_METHOD_REGEXP).to_set
      allowed_writer_methods -= INVALID_WRITER_METHODS
      allowed_writer_methods.freeze
    end
end

#attribute(*args) ⇒ self

Defines an attribute on an object’s class

Examples:

class Book
  include Virtus

  attribute :title,        String
  attribute :author,       String
  attribute :published_at, DateTime
  attribute :page_count,   Integer
end

Parameters:

  • name (Symbol)

    the name of an attribute

  • type (Class)

    the type class of an attribute

  • options (#to_hash)

    the extra options hash

Returns:

  • (self)

See Also:



51
52
53
54
55
56
# File 'lib/virtus/class_methods.rb', line 51

def attribute(*args)
  attribute = Attribute.build(*args)
  attribute.define_accessor_methods(virtus_attributes_accessor_module)
  virtus_add_attribute(attribute)
  self
end

#attributesAttributeSet

Returns all the attributes defined on a Class

Examples:

class User
  include Virtus

  attribute :name, String
  attribute :age,  Integer
end

User.attributes  # =>

TODO: implement inspect so the output is not cluttered - solnic

Returns:



75
76
77
78
79
80
81
# File 'lib/virtus/class_methods.rb', line 75

def attributes
  return @attributes if defined?(@attributes)
  superclass  = self.superclass
  method      = __method__
  parent      = superclass.send(method) if superclass.respond_to?(method)
  @attributes = AttributeSet.new(parent)
end