aboutsummaryrefslogtreecommitdiffstats
path: root/activerecord
diff options
context:
space:
mode:
authorGuillermo Iguaran <guilleiguaran@gmail.com>2012-03-10 19:39:13 -0500
committerGuillermo Iguaran <guilleiguaran@gmail.com>2012-03-29 17:48:35 -0500
commit01ede9a211d91d415488d42ff8015809de2ac497 (patch)
tree4233a1a57d72a44257dc539a565649ca15226375 /activerecord
parent1555023973d2f60050f16b055335abc4e038e20f (diff)
downloadrails-01ede9a211d91d415488d42ff8015809de2ac497.tar.gz
rails-01ede9a211d91d415488d42ff8015809de2ac497.tar.bz2
rails-01ede9a211d91d415488d42ff8015809de2ac497.zip
Add ActiveRecord::Base#slice to slice method calls
Diffstat (limited to 'activerecord')
-rw-r--r--activerecord/lib/active_record/core.rb6
-rw-r--r--activerecord/test/cases/base_test.rb12
2 files changed, 18 insertions, 0 deletions
diff --git a/activerecord/lib/active_record/core.rb b/activerecord/lib/active_record/core.rb
index 9a2f859fc7..76c424e8b4 100644
--- a/activerecord/lib/active_record/core.rb
+++ b/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
@@ -326,6 +327,11 @@ module ActiveRecord
"#<#{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
diff --git a/activerecord/test/cases/base_test.rb b/activerecord/test/cases/base_test.rb
index ff39285f62..f0fbca190c 100644
--- a/activerecord/test/cases/base_test.rb
+++ b/activerecord/test/cases/base_test.rb
@@ -2057,4 +2057,16 @@ class BasicsTest < ActiveRecord::TestCase
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