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

Add values_at attribute method for active_record

This commit is contained in:
Guillaume Briday 2019-07-29 00:49:31 +02:00 committed by Eugene Kenny
parent 871073c4a9
commit 458fff60ce
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.
*Marcelo Lauxen*

View file

@ -601,6 +601,11 @@ module ActiveRecord
Hash[methods.flatten.map! { |method| [method, public_send(method)] }].with_indifferent_access
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
# +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

View file

@ -1411,6 +1411,21 @@ class BasicsTest < ActiveRecord::TestCase
assert_equal attrs, topic.slice(attrs.keys)
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
company = Company.new
company.description << "foo"