提交 01ede9a2 编写于 作者: G Guillermo Iguaran

Add ActiveRecord::Base#slice to slice method calls

上级 15550239
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
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册