Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Whitelisting safe_constantize (ActiveSupport::Inflector) method #20

Merged
merged 1 commit into from
Dec 21, 2014
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions lib/did_you_mean/core_ext/name_error.rb
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
class NameError
attr_reader :frame_binding

WHITE_LISTED_CALLERS = %w{safe_constantize}

begin
require "active_support/core_ext/name_error"

Expand All @@ -12,6 +14,7 @@ def missing_name
rescue LoadError; end

def to_s_with_did_you_mean
return original_message if caller_is_whitelisted?
original_message + did_you_mean?.to_s rescue original_message
end

Expand All @@ -29,4 +32,15 @@ def suggestions
def finder
@finder ||= DidYouMean.finders[self.class.to_s].new(self)
end

private

def caller_is_whitelisted?
backtrace_methods.any?{ |method| WHITE_LISTED_CALLERS.include? method }
end

def backtrace_methods
regex_parse_trace = /^(.+?):(\d+)(|:in `(.+)')$/
exception.backtrace.map{ |trace| trace.match(regex_parse_trace)[4] }.uniq
end
end
22 changes: 22 additions & 0 deletions test/name_error_extension_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -21,4 +21,26 @@ def test_message?
assert_match "Y U SO SLOW?", @error.to_s
assert_match "Y U SO SLOW?", @error.message
end

def test_whitelisted_message?
@error = safe_constantize
assert @error.to_s =~ /doesnt_exist/
assert @error.message =~ /doesnt_exist/
end

def test_note_whitelisted_message?
@error = not_safe_constantize
assert_match "Y U SO SLOW?", @error.to_s
assert_match "Y U SO SLOW?", @error.message
end

private

def safe_constantize
assert_raises(NAME_ERROR){ doesnt_exist }
end

def not_safe_constantize
assert_raises(NAME_ERROR){ doesnt_exist }
end
end