Module: Virtus::InstanceMethods

Defined in:
lib/virtus/instance_methods.rb

Overview

Instance methods that are added when you include Virtus

Defined Under Namespace

Modules: Constructor, MassAssignment

Instance Method Summary collapse

Instance Method Details

#[](name) ⇒ Object

Returns a value of the attribute with the given name

Examples:

class User
  include Virtus

  attribute :name, String
end

user = User.new(:name => 'John')
user[:name]  # => "John"

Parameters:

  • name (Symbol)

    a name of an attribute

Returns:

  • (Object)

    a value of an attribute



94
95
96
# File 'lib/virtus/instance_methods.rb', line 94

def [](name)
  public_send(name)
end

#[]=(name, value) ⇒ Object

Sets a value of the attribute with the given name

Examples:

class User
  include Virtus

  attribute :name, String
end

user = User.new
user[:name] = "John"  # => "John"
user.name             # => "John"

Parameters:

  • name (Symbol)

    a name of an attribute

  • value (Object)

    a value to be set

Returns:

  • (Object)

    the value set on an object



121
122
123
# File 'lib/virtus/instance_methods.rb', line 121

def []=(name, value)
  public_send("#{name}=", value)
end

#freezeself

Freeze object

Examples:


class User
  include Virtus

  attribute :name, String
  attribute :age,  Integer
end

user = User.new(:name => 'John', :age => 28)
user.frozen? # => false
user.freeze
user.frozen? # => true

Returns:

  • (self)


146
147
148
149
# File 'lib/virtus/instance_methods.rb', line 146

def freeze
  set_default_attributes!
  super
end

#reset_attribute(attribute_name) ⇒ self

Reset an attribute to its default

Examples:


class User
  include Virtus

  attribute :age,  Integer, default: 21
end

user = User.new(:name => 'John', :age => 28)
user.age = 30
user.age # => 30
user.reset_attribute(:age)
user.age # => 21

Returns:

  • (self)


172
173
174
175
176
# File 'lib/virtus/instance_methods.rb', line 172

def reset_attribute(attribute_name)
  attribute = attribute_set[attribute_name]
  attribute.set_default_value(self) if attribute
  self
end

#set_default_attributesself

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.

Set default attributes

Returns:

  • (self)


183
184
185
186
# File 'lib/virtus/instance_methods.rb', line 183

def set_default_attributes
  attribute_set.set_defaults(self)
  self
end

#set_default_attributes!self

Set default attributes even lazy ones

Returns:

  • (self)


193
194
195
196
# File 'lib/virtus/instance_methods.rb', line 193

def set_default_attributes!
  attribute_set.set_defaults(self, proc { |object, attribute| attribute.defined?(object) })
  self
end