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!"


145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
# File 'lib/rails/pattern_matching.rb', line 145

def deconstruct_keys(keys)
  if keys
    # If we've been given keys, then we're going to filter down to just the
    # attributes that were given for this object.
    keys.each_with_object({}) do |key, deconstructed|
      string_key = key.to_s

      # If the user provided a key that doesn't match an attribute, then we
      # do not add it to the result hash, and the match will fail.
      if attribute_method?(string_key)
        deconstructed[key] = public_send(string_key)
      end
    end
  else
    # If we haven't been given keys, then the user wants to grab up all of the
    # attributes for this object.
    attributes.transform_keys(&:to_sym)
  end
end