Module: AttributeGuard::ClassMethods

Defined in:
lib/attribute_guard.rb

Instance Method Summary collapse

Instance Method Details

#lock_attributes(*attributes, error: :locked, mode: :error) ⇒ void

This method returns an undefined value.

Locks the given attributes so that they cannot be changed directly. Subclasses inherit the locked attributes from their parent classes.

You can optionally specify a mode of what to do when a locked attribute is changed. The default is to add an error to the model, but you can also specify :warn to log a warning or a Proc to call with the record and attribute name.

Parameters:

  • attributes (Array<Symbol, String>)

    the attributes to lock

  • error (String, Symbol, Boolean) (defaults to: :locked)

    the error message to use in validate errors

  • mode (Symbol, Proc) (defaults to: :error)

    mode to use when a locked attribute is changed



112
113
114
115
116
117
118
119
120
121
# File 'lib/attribute_guard.rb', line 112

def lock_attributes(*attributes, error: :locked, mode: :error)
  locked = locked_attributes.dup
  error = error.dup.freeze if error.is_a?(String)

  attributes.flatten.each do |attribute|
    locked[attribute.to_s] = [error, mode]
  end

  self.locked_attributes = locked
end

#locked_attribute_namesArray<String>

Returns the names of the locked attributes.

Returns:

  • (Array<String>)

    the names of the locked attributes.



126
127
128
# File 'lib/attribute_guard.rb', line 126

def locked_attribute_names
  locked_attributes.keys
end