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


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

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


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

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)

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

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)

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

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)

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

def set_default_attributes
  attribute_set.set_defaults(self)
  self
end

#set_default_attributes!self

Set default attributes even lazy ones

Returns:

  • (self)

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

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