From: Tom Hughes Date: Mon, 24 Jun 2013 21:44:17 +0000 (+0100) Subject: Extract common code for parsing floats X-Git-Tag: live~4930 X-Git-Url: https://git.openstreetmap.org/rails.git/commitdiff_plain/f03c8637f7377f34d31f4b0bd88caa4a9e7a9570 Extract common code for parsing floats --- diff --git a/app/controllers/notes_controller.rb b/app/controllers/notes_controller.rb index 9c6eb9457..3eb1ac3f9 100644 --- a/app/controllers/notes_controller.rb +++ b/app/controllers/notes_controller.rb @@ -59,16 +59,8 @@ class NotesController < ApplicationController raise OSM::APIBadUserInput.new("No text was given") if params[:text].blank? # Extract the arguments - begin - lon = Float(params[:lon]) - rescue - raise OSM::APIBadUserInput.new("lon was not a number") - end - begin - lat = Float(params[:lat]) - rescue - raise OSM::APIBadUserInput.new("lat was not a number") - end + lon = OSM.parse_float(params[:lon], OSM::APIBadUserInput, "lon was not a number") + lat = OSM.parse_float(params[:lat], OSM::APIBadUserInput, "lat was not a number") comment = params[:text] # Include in a transaction to ensure that there is always a note_comment for every note diff --git a/app/models/node.rb b/app/models/node.rb index 775f1fd3b..81b910f37 100644 --- a/app/models/node.rb +++ b/app/models/node.rb @@ -83,16 +83,8 @@ class Node < ActiveRecord::Base raise OSM::APIBadXMLError.new("node", pt, "lat missing") if pt['lat'].nil? raise OSM::APIBadXMLError.new("node", pt, "lon missing") if pt['lon'].nil? - begin - node.lat = Float(pt['lat']) - rescue - raise OSM::APIBadXMLError.new("node", pt, "lat not a number") - end - begin - node.lon = Float(pt['lon']) - rescue - raise OSM::APIBadXMLError.new("node", pt, "lon not a number") - end + node.lat = OSM.parse_float(pt['lat'], OSM::APIBadXMLError, "node", pt, "lat not a number") + node.lon = OSM.parse_float(pt['lon'], OSM::APIBadXMLError, "node", pt, "lon not a number") raise OSM::APIBadXMLError.new("node", pt, "Changeset id is missing") if pt['changeset'].nil? node.changeset_id = pt['changeset'].to_i diff --git a/lib/osm.rb b/lib/osm.rb index d4c13ad7f..4a6237b12 100644 --- a/lib/osm.rb +++ b/lib/osm.rb @@ -550,6 +550,13 @@ module OSM return nil end + # Parse a float, raising a specified exception on failure + def self.parse_float(str, klass, *args) + Float(str) + rescue + raise klass.new(*args) + end + # Construct a random token of a given length def self.make_token(length = 30) chars = 'abcdefghijklmnopqrtuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'