Example refactoring of https://github.com/halostatue/mime-types/blob/d4f761ded1/lib/mime/type.rb#L155 for a reply to https://news.ycombinator.com/item?id=7339958.
class MIME::Type | |
# Compares the MIME::Type based on how reliable it is before doing a | |
# normal <=> comparison. Used by MIME::Types#[] to sort types. | |
def priority_compare(other) | |
PriorityComparison.new(self, other).value | |
end | |
end |
class MIME::Type::PriorityComparison | |
def initialize(one, two) | |
@one, @two = one, two | |
end | |
def value | |
if simplified_value.zero? | |
complex_value | |
else | |
simplified_value | |
end | |
end | |
private | |
def simplified_value | |
one.simplified <=> two.simplified | |
end | |
def complex_value | |
if one.registered? != two.registered? | |
one.registered? ? -1 : 1 # registered < unregistered | |
elsif one.platform? != two.platform? | |
one.platform? ? 1 : -1 # generic < platform | |
elsif one.complete? != two.complete? | |
one.complete? ? -1 : 1 # complete < incomplete | |
elsif one.obsolete? != two.obsolete? | |
one.obsolete? ? 1 : -1 # current < obsolete | |
elsif one.obsolete? && (one.use_instead != two.use_instead) | |
use_instead_value | |
else | |
0 | |
end | |
def use_instead_value | |
if one.use_instead.nil? | |
1 | |
elsif two.use_instead.nil? | |
-1 | |
else | |
one.use_instead <=> two.use_instead | |
end | |
end | |
end | |
def attr_reader :one, :two | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This comment has been minimized.
Intended as a kind of minimal extraction/refactoring – extracting the object and breaking up the nested conditionals. More could be done, of course, but with diminishing returns.