Skip to content

Instantly share code, notes, and snippets.

@henrik henrik/0-mime-type.rb
Last active Aug 29, 2015

Embed
What would you like to do?
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
@henrik

This comment has been minimized.

Copy link
Owner Author

commented Mar 4, 2014

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.