Module: ActiveModel::AttributeMethods

Defined in:
lib/rails/pattern_matching.rb

Instance Method Summary collapse

Instance Method Details

#deconstruct_keys(keys) ⇒ Object

Returns a hash of attributes for the given keys. Provides the pattern matching interface for matching against hash patterns. For example:

class Person
  include ActiveModel::AttributeMethods

  attr_accessor :name
  define_attribute_method :name
end

def greeting_for(person)
  case person
  in { name: "Mary" }
    "Welcome back, Mary!"
  in { name: }
    "Welcome, stranger!"
  end
end

person = Person.new
person.name = "Mary"
greeting_for(person) # => "Welcome back, Mary!"

person = Person.new
person.name = "Bob"
greeting_for(person) # => "Welcome, stranger!"


130
131
132
133
134
135
136
137
138
# File 'lib/rails/pattern_matching.rb', line 130

def deconstruct_keys(keys)
  keys.each_with_object({}) do |key, deconstructed|
    string_key = key.to_s

    if attribute_method?(string_key)
      deconstructed[key] = public_send(string_key)
    end
  end
end