0

I've got a mobile app that makes an api call. In the api call, I'm sending the version number of the app because the returned json could be a bit different depending on the api version.

So when I have app version 2.4.1 and I need to check against the current api version 2.4.4, I everything is fine because I'm using

if user_version.gsub('.','').to_i < server_version.gsub('.','').to_i
 //the user version is not current, ask them to update
end

the problem comes in down the line when somebody releases version 2.5. With the above code, the user would have 2.4.4 which gets translated to 244 which is larger than the server side 2.5 or 25.

How would you check this to cover these instances?

pedalpete
  • 21,076
  • 45
  • 128
  • 239

2 Answers2

0

You can parse the version numbers using a regex, as detailed here: A regex for version number parsing

This one will do: ^(?:(\d+)\.)?(?:(\d+)\.)?(\*|\d+)$

So:

version_regex = /^(?:(\d+)\.)?(?:(\d+)\.)?(\*|\d+)$/
user_version_array = user_version.match(version_regex)[1..3].compact.map(&:to_i)
server_version_array = server_version.match(version_regex)[1..3].compact.map(&:to_i)

For the sake of DRYness, you might want to break this out into a helper method:

def parse_version(str)
  version_regex = /^(?:(\d+)\.)?(?:(\d+)\.)?(\*|\d+)$/
  str.match(version_regex)[1..3].compact.map(&:to_i)
end

For the example of user_version = '2.4.4' and server_version = '2.5', that gives you the arrays:

user_version_array = [2,4,2]
server_version_array = [2,5]

You can then easily iterate over these to compare:

compliant_version = true
(0..2).each do |i|
  if (user_version_array[i] || 0) < (server_version_array[i] || 0)
    compliant_version = false
  end
end
Community
  • 1
  • 1
MrTheWalrus
  • 9,670
  • 2
  • 42
  • 66
0

Turns out this is included as a class in Rails http://rubygems.rubyforge.org/rubygems-update/Gem/Version.html

much easier than writing it yourself. :)

pedalpete
  • 21,076
  • 45
  • 128
  • 239