Skip to content

Commit

Permalink
Merge pull request rails#5345 from guilleiguaran/ar-slice
Browse files Browse the repository at this point in the history
post.slice(:title, :content) # => { title: "Hello", content: "World" }
  • Loading branch information
jeremy committed Mar 29, 2012
2 parents 1555023 + bb2e2d8 commit 648248b
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 0 deletions.
5 changes: 5 additions & 0 deletions activerecord/CHANGELOG.md
@@ -1,5 +1,10 @@
## Rails 4.0.0 (unreleased) ##

* Added ActiveRecord::Base#slice to return a hash of the given methods with
their names as keys and returned values as values.

*Guillermo Iguaran*

* Deprecate eager-evaluated scopes.

Don't use this:
Expand Down
6 changes: 6 additions & 0 deletions activerecord/lib/active_record/core.rb
@@ -1,4 +1,5 @@
require 'active_support/concern'
require 'active_support/core_ext/hash/indifferent_access'
require 'thread'

module ActiveRecord
Expand Down Expand Up @@ -326,6 +327,11 @@ def inspect
"#<#{self.class} #{inspection}>"
end

# Returns a hash of the given methods with their names as keys and returned values as values.
def slice(*methods)
Hash[methods.map { |method| [method, public_send(method)] }].with_indifferent_access
end

private

# Under Ruby 1.9, Array#flatten will call #to_ary (recursively) on each of the elements
Expand Down
12 changes: 12 additions & 0 deletions activerecord/test/cases/base_test.rb
Expand Up @@ -2057,4 +2057,16 @@ def type_cast value
def test_typecasting_aliases
assert_equal 10, Topic.select('10 as tenderlove').first.tenderlove
end

def test_slice
company = Company.new(:rating => 1, :name => "37signals", :firm_name => "37signals")
hash = company.slice(:name, :rating, "arbitrary_method")
assert_equal hash[:name], company.name
assert_equal hash['name'], company.name
assert_equal hash[:rating], company.rating
assert_equal hash['arbitrary_method'], company.arbitrary_method
assert_equal hash[:arbitrary_method], company.arbitrary_method
assert_nil hash[:firm_name]
assert_nil hash['firm_name']
end
end

0 comments on commit 648248b

Please sign in to comment.