From f03c8637f7377f34d31f4b0bd88caa4a9e7a9570 Mon Sep 17 00:00:00 2001 From: Tom Hughes Date: Mon, 24 Jun 2013 22:44:17 +0100 Subject: [PATCH 1/1] Extract common code for parsing floats --- app/controllers/notes_controller.rb | 12 ++---------- app/models/node.rb | 12 ++---------- lib/osm.rb | 7 +++++++ 3 files changed, 11 insertions(+), 20 deletions(-) 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' -- 2.39.5