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:
commit
0a608bd987
3 changed files with 34 additions and 0 deletions
|
@ -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*
|
||||
|
|
|
@ -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
|
||||
|
|
|
@ -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"
|
||||
|
|
Loading…
Reference in a new issue