Module: Mongoid::Attributes::ClassMethods

Defined in:
build/mongoid-7.3/lib/mongoid/attributes.rb

Instance Method Summary collapse

Instance Method Details

#alias_attribute(name, original) ⇒ Object

Alias the provided name to the original field. This will provide an aliased getter, setter, existence check, and all dirty attribute methods.

Examples:

Alias the attribute.

class Product
  include Mongoid::Document
  field :price, :type => Float
  alias_attribute :cost, :price
end

Parameters:

  • name (Symbol)

    The new name.

  • original (Symbol)

    The original name.

Since:

  • 2.3.0



321
322
323
324
325
326
327
328
329
330
331
332
333
334
# File 'build/mongoid-7.3/lib/mongoid/attributes.rb', line 321

def alias_attribute(name, original)
  aliased_fields[name.to_s] = original.to_s

  alias_method name, original
  alias_method "#{name}=", "#{original}="
  alias_method "#{name}?", "#{original}?"
  alias_method "#{name}_change", "#{original}_change"
  alias_method "#{name}_changed?", "#{original}_changed?"
  alias_method "reset_#{name}!", "reset_#{original}!"
  alias_method "reset_#{name}_to_default!", "reset_#{original}_to_default!"
  alias_method "#{name}_was", "#{original}_was"
  alias_method "#{name}_will_change!", "#{original}_will_change!"
  alias_method "#{name}_before_type_cast", "#{original}_before_type_cast"
end

#unalias_attribute(name) ⇒ Object

Removes a field alias.

Parameters:

  • name (Symbol)

    The aliased field name to remove.



339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
# File 'build/mongoid-7.3/lib/mongoid/attributes.rb', line 339

def unalias_attribute(name)
  unless aliased_fields.delete(name.to_s)
    raise AttributeError, "Field #{name} is not an aliased field"
  end

  remove_method name
  remove_method "#{name}="
  remove_method "#{name}?"
  remove_method "#{name}_change"
  remove_method "#{name}_changed?"
  remove_method "reset_#{name}!"
  remove_method "reset_#{name}_to_default!"
  remove_method "#{name}_was"
  remove_method "#{name}_will_change!"
  remove_method "#{name}_before_type_cast"
end