Skip to content

Commit

Permalink
Merge pull request #36481 from guillaumebriday/master
Browse files Browse the repository at this point in the history
Add values_at attribute method for active_record
  • Loading branch information
eugeneius committed Oct 19, 2020
2 parents 871073c + 458fff6 commit 0a608bd
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 0 deletions.
14 changes: 14 additions & 0 deletions activerecord/CHANGELOG.md
@@ -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*
Expand Down
5 changes: 5 additions & 0 deletions activerecord/lib/active_record/core.rb
Expand Up @@ -601,6 +601,11 @@ def slice(*methods)
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
Expand Down
15 changes: 15 additions & 0 deletions activerecord/test/cases/base_test.rb
Expand Up @@ -1411,6 +1411,21 @@ def test_slice_accepts_array_argument
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"
Expand Down

0 comments on commit 0a608bd

Please sign in to comment.