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

Better diff coloring #169

Merged
merged 3 commits into from Aug 25, 2012
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
31 changes: 19 additions & 12 deletions lib/rspec/expectations/differ.rb
Expand Up @@ -63,30 +63,37 @@ def context_lines
3
end

def color(text, code)
"\e[#{code}m#{text}\e[0m"
def color(text, color_code)
"\e[#{color_code}m#{text}\e[0m"
end

def red(text)
color(text, 31)
end

def green(text)
color(text, 32)
end

def blue(text)
color(text, 34)
end
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Honestly, I find this to be less readable and succinct than what you had before. I don't have a preference for color(text, red) over red(text) as an API (both seem equally fine to me), but using a hash and define_method adds extra indirection over what you had before. If you want the separate methods for each color, I'd prefer:

def red
  color(text, 31)
end

def green
  color(text, 32)
end

def blue
  color(text, 34)
end

I know on 1.8 that methods defined with define_method are slower when called than methods defined with def. Not sure about 1.9 (I haven't benchmarked it), but I expect it's still slower. So that's another reason to prefer def over define_method for this case.


def color_diff(diff)
return diff unless RSpec::Matchers.configuration.color?

red = 31
green = 32
blue = 34

lines = diff.lines.map do |line|
diff.lines.map { |line|
case line[0].chr
when "+"
color(line, green)
green line
when "-"
color(line, red)
red line
when "@"
line[1].chr == "@" ? color(line, blue) : line
line[1].chr == "@" ? blue(line) : line
else
line
end
end
lines.join
}.join
end

def object_to_string(object)
Expand Down
2 changes: 1 addition & 1 deletion lib/rspec/matchers/configuration.rb
Expand Up @@ -43,7 +43,7 @@ def syntax
# fallback if rspec core not available
if defined?(RSpec::Core)
def color?
RSpec.configuration.color
RSpec.configuration.color_enabled?
end
else
attr_writer :color
Expand Down