instance method define_attribute_method

Ruby on Rails 7.2.3

Since v3.1.12

Available in: v3.1.12 v3.2.22.5 v4.0.13 v4.1.16 v4.2.9 v5.2.8.1 v6.0.6 v6.1.7.10 v7.0.10 v7.1.6 v7.2.3 v8.0.4 v8.1.2

Signature

define_attribute_method(attr_name, _owner: generated_attribute_methods, as: attr_name)

Declares an attribute that should be prefixed and suffixed by ActiveModel::AttributeMethods.

To use, pass an attribute name (as string or symbol). Be sure to declare define_attribute_method after you define any prefix, suffix or affix method, or they will not hook in.

class Person
  include ActiveModel::AttributeMethods

  attr_accessor :name
  attribute_method_suffix '_short?'

  # Call to define_attribute_method must appear after the
  # attribute_method_prefix, attribute_method_suffix or
  # attribute_method_affix declarations.
  define_attribute_method :name

  private
    def attribute_short?(attr)
      send(attr).length < 5
    end
end

person = Person.new
person.name = 'Bob'
person.name        # => "Bob"
person.name_short? # => true

Parameters

attr_name req
_owner key = generated_attribute_methods
as key = attr_name
Source
# File activemodel/lib/active_model/attribute_methods.rb, line 311
      def define_attribute_method(attr_name, _owner: generated_attribute_methods, as: attr_name)
        ActiveSupport::CodeGenerator.batch(_owner, __FILE__, __LINE__) do |owner|
          attribute_method_patterns.each do |pattern|
            define_attribute_method_pattern(pattern, attr_name, owner: owner, as: as)
          end
          attribute_method_patterns_cache.clear
        end
      end

Defined in activemodel/lib/active_model/attribute_methods.rb line 311 · View on GitHub · Improve this page · Find usages on GitHub

Defined in ActiveModel::AttributeMethods::ClassMethods

Type at least 2 characters to search.

↑↓ navigate · open · esc close