1
0
Fork 0
mirror of https://github.com/rails/rails.git synced 2022-11-09 12:12:34 -05:00

Merge pull request #36481 from guillaumebriday/master

Add values_at attribute method for active_record
This commit is contained in:
Eugene Kenny 2020-10-19 17:31:59 +01:00 committed by GitHub
commit 0a608bd987
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 34 additions and 0 deletions

View file

@ -1,3 +1,17 @@
* Add `values_at` method.
Returns an array containing the values associated with the given methods.
```ruby
topic = Topic.first
topic.values_at(:title, :author_name)
# => ["Budget", "Jason"]
```
Similar to `Hash#values_at` but on an Active Record instance.
*Guillaume Briday*
* Fix `read_attribute_before_type_cast` to consider attribute aliases. * Fix `read_attribute_before_type_cast` to consider attribute aliases.
*Marcelo Lauxen* *Marcelo Lauxen*

View file

@ -601,6 +601,11 @@ module ActiveRecord
Hash[methods.flatten.map! { |method| [method, public_send(method)] }].with_indifferent_access Hash[methods.flatten.map! { |method| [method, public_send(method)] }].with_indifferent_access
end end
# Returns an array of the values returned by the given methods.
def values_at(*methods)
methods.flatten.map! { |method| public_send(method) }
end
private private
# +Array#flatten+ will call +#to_ary+ (recursively) on each of the elements of # +Array#flatten+ will call +#to_ary+ (recursively) on each of the elements of
# the array, and then rescues from the possible +NoMethodError+. If those elements are # the array, and then rescues from the possible +NoMethodError+. If those elements are

View file

@ -1411,6 +1411,21 @@ class BasicsTest < ActiveRecord::TestCase
assert_equal attrs, topic.slice(attrs.keys) assert_equal attrs, topic.slice(attrs.keys)
end end
def test_values_at
company = Company.new(name: "37signals", rating: 1)
assert_equal [ "37signals", 1, "I am Jack's profound disappointment" ],
company.values_at(:name, :rating, :arbitrary_method)
assert_equal [ "I am Jack's profound disappointment", 1, "37signals" ],
company.values_at(:arbitrary_method, :rating, :name)
end
def test_values_at_accepts_array_argument
topic = Topic.new(title: "Budget", author_name: "Jason")
assert_equal %w( Budget Jason ), topic.values_at(%w( title author_name ))
end
def test_default_values_are_deeply_dupped def test_default_values_are_deeply_dupped
company = Company.new company = Company.new
company.description << "foo" company.description << "foo"