Permalink
Browse files

speed up is_collection? check

  • Loading branch information...
1 parent ff9c173 commit 4d0e159f8c4b597aeca24f4b1467650e4c56effb @dgynn dgynn committed Jun 12, 2016
Showing with 8 additions and 6 deletions.
  1. +1 −5 lib/rabl/helpers.rb
  2. +7 −1 test/helpers_test.rb
View
@@ -1,11 +1,7 @@
require 'active_support/inflector' # for the sake of pluralizing
-require 'set'
module Rabl
module Helpers
- # Set of class names known to be objects, not collections
- KNOWN_OBJECT_CLASSES = Set.new(['Struct', 'Hashie::Mash'])
-
# data_object(data) => <AR Object>
# data_object(@user => :person) => @user
# data_object(:user => :person) => @_object.send(:user)
@@ -86,7 +82,7 @@ def is_object?(obj, follow_symbols = true)
def is_collection?(obj, follow_symbols = true)
data_obj = follow_symbols ? data_object(obj) : obj
data_obj && data_obj.respond_to?(:map) && data_obj.respond_to?(:each) &&
- obj.class.ancestors.none? { |a| KNOWN_OBJECT_CLASSES.include?(a.name) }
+ !(data_obj.is_a?(Struct) || defined?(Hashie::Mash) && data_obj.is_a?(Hashie::Mash))
end
# Returns the context_scope wrapping this engine, used for retrieving data, invoking methods, etc
@@ -122,9 +122,15 @@ class TestHelperMethods
@helper_class.is_collection?([@user])
end.equals(true)
- asserts "returns true for an array" do
+ asserts "returns false for a Hashie::Mash with 1 key" do
obj = Hashie::Mash.new({:name => 'hello'})
@helper_class.is_collection?(obj)
end.equals(false)
+
+ asserts "returns false for a Hashie::Mash with 2 keys" do
+ obj = Hashie::Mash.new({:name => 'hello', :key2 => 'key2'})
+ @helper_class.is_collection?(obj)
+ end.equals(false)
+
end # is_collection method
end

0 comments on commit 4d0e159

Please sign in to comment.