Skip to content

Instantly share code, notes, and snippets.

@henrik
Last active August 29, 2015 13:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save henrik/9355101 to your computer and use it in GitHub Desktop.
Save henrik/9355101 to your computer and use it in GitHub Desktop.
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
Copy link
Author

henrik 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