Method: ActiveModel::AttributeMethods::ClassMethods#define_attribute_method

Defined in:
lib/active_model/attribute_methods.rb

#define_attribute_method(attr_name) ⇒ Object

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


284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
# File 'lib/active_model/attribute_methods.rb', line 284

def define_attribute_method(attr_name)
  attribute_method_matchers.each do |matcher|
    method_name = matcher.method_name(attr_name)

    unless instance_method_already_implemented?(method_name)
      generate_method = "define_method_#{matcher.method_missing_target}"

      if respond_to?(generate_method, true)
        send(generate_method, attr_name.to_s)
      else
        define_proxy_call true, generated_attribute_methods, method_name, matcher.method_missing_target, attr_name.to_s
      end
    end
  end
  attribute_method_matchers_cache.clear
end