Permalink
Browse files

Add ActiveRecord::Base#slice to slice method calls

  • Loading branch information...
1 parent 1555023 commit 01ede9a211d91d415488d42ff8015809de2ac497 @guilleiguaran guilleiguaran committed Mar 11, 2012
Showing with 18 additions and 0 deletions.
  1. +6 −0 activerecord/lib/active_record/core.rb
  2. +12 −0 activerecord/test/cases/base_test.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 @@ 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
@@ -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 01ede9a

Please sign in to comment.