instance method define_attribute_methods

Ruby on Rails 3.0.20

Since v3.0.20

Available in: v3.0.20 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_methods(attr_names)

Declares a the attributes that should be prefixed and suffixed by ActiveModel::AttributeMethods.

To use, pass in an array of attribute names (as strings or symbols), be sure to declare define_attribute_methods after you define any prefix, suffix or affix methods, or they will not hook in.

class Person

  include ActiveModel::AttributeMethods
  attr_accessor :name, :age, :address
  attribute_method_prefix 'clear_'

  # Call to define_attribute_methods must appear after the
  # attribute_method_prefix, attribute_method_suffix or
  # attribute_method_affix declares.
  define_attribute_methods [:name, :age, :address]

  private

  def clear_attribute(attr)
    ...
  end
end

Parameters

attr_names req
Source
# File activemodel/lib/active_model/attribute_methods.rb, line 276
      def define_attribute_methods(attr_names)
        return if attribute_methods_generated?
        attr_names.each do |attr_name|
          attribute_method_matchers.each do |matcher|
            unless instance_method_already_implemented?(matcher.method_name(attr_name))
              generate_method = "define_method_#{matcher.prefix}attribute#{matcher.suffix}"

              if respond_to?(generate_method)
                send(generate_method, attr_name)
              else
                method_name = matcher.method_name(attr_name)

                generated_attribute_methods.module_eval <<-RUBY, __FILE__, __LINE__ + 1
                  if method_defined?('#{method_name}')
                    undef :'#{method_name}'
                  end
                RUBY

                if method_name.to_s =~ COMPILABLE_REGEXP
                  generated_attribute_methods.module_eval <<-RUBY, __FILE__, __LINE__ + 1
                    def #{method_name}(*args)
                      send(:#{matcher.method_missing_target}, '#{attr_name}', *args)
                    end
                  RUBY
                else
                  generated_attribute_methods.module_eval <<-RUBY, __FILE__, __LINE__ + 1
                    define_method('#{method_name}') do |*args|
                      send('#{matcher.method_missing_target}', '#{attr_name}', *args)
                    end
                  RUBY
                end
              end
            end
          end
        end
        @attribute_methods_generated = true
      end

Defined in activemodel/lib/active_model/attribute_methods.rb line 276 · 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