Class: ActiveRecord::Base

Inherits:
Object
  • Object
show all
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 < ActiveRecord::Base
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!"


49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/rails/pattern_matching.rb', line 49

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

    if attribute_method?(method)
      # Here we're pattern matching against an attribute method. We're
      # going to use the [] method so that we either get the value or
      # raise an error for a missing attribute in case it wasn't loaded.
      deconstructed[key] = public_send(method)
    elsif self.class.reflect_on_association(method)
      # Here we're going to pattern match against an association. We're
      # going to use the main interface for that association which can
      # be further pattern matched later.
      deconstructed[key] = public_send(method)
    end
  end
end