From f39609d54dfd43c6b6a410067afcf6416b492161 Mon Sep 17 00:00:00 2001 From: Michael Herold Date: Fri, 23 Oct 2015 14:39:16 -0500 Subject: Ensure that MethodQuery methods return booleans The documentation about the MethodQuery module spells out the expected behavior. While the spec suite appeared to be testing the same, the RSpec matchers were not actually checking the behavior properly. This lead to a divergence between the expected behavior, as outlined in the module documentation, and the actual behavior, as tested in the spec suite. This is the reason that #299 is happening: the expected behavior is not the actual behavior. I have included a test for #299 to show that it works as expected in this branch. This change makes the spec suite match the behavior in the module documentation, then modifies the methods to match the documentated specification. Lastly, I took the time to clean up the MethodQuery module for two reasons: 1. The old implementation used Regexps on the stringified method names, which is unnecessary since we have the wonderful `String#end_with?` method to check the suffix of a strings. 2. The old logic was difficult to reason through, so I clarified the intent of the methods by reducing the complexity of the conditionals and extracting meaningful methods where possible. --- lib/hashie/extensions/method_access.rb | 35 +++++++++++++++++++++++++++++----- 1 file changed, 30 insertions(+), 5 deletions(-) (limited to 'lib') diff --git a/lib/hashie/extensions/method_access.rb b/lib/hashie/extensions/method_access.rb index 9c3d537..0ed2b22 100644 --- a/lib/hashie/extensions/method_access.rb +++ b/lib/hashie/extensions/method_access.rb @@ -107,16 +107,41 @@ module Hashie # h.hji? # => NoMethodError module MethodQuery def respond_to?(name, include_private = false) - return true if name.to_s =~ /(.*)\?$/ && (key?(Regexp.last_match[1]) || key?(Regexp.last_match[1].to_sym)) - super + if query_method?(name) && indifferent_key?(key_from_query_method(name)) + true + else + super + end end def method_missing(name, *args) - if args.empty? && name.to_s =~ /(.*)\?$/ && (key?(Regexp.last_match[1]) || key?(Regexp.last_match[1].to_sym)) - return self[Regexp.last_match[1]] || self[Regexp.last_match[1].to_sym] + return super unless args.empty? + + if query_method?(name) + key = key_from_query_method(name) + if indifferent_key?(key) + !!(self[key] || self[key.to_sym]) + else + super + end + else + super end + end - super + private + + def indifferent_key?(name) + name = name.to_s + key?(name) || key?(name.to_sym) + end + + def key_from_query_method(query_method) + query_method.to_s[0..-2] + end + + def query_method?(name) + name.to_s.end_with?('?') end end -- cgit v1.2.1