From 24ed2c992d8a7397183b6cf0f36e0845b2b17d6b Mon Sep 17 00:00:00 2001 From: Anton Maminov Date: Fri, 5 Apr 2024 13:41:47 +0300 Subject: [PATCH] make ip_address optional --- src/ipapi.cr | 33 ++++++++------------------------- 1 file changed, 8 insertions(+), 25 deletions(-) diff --git a/src/ipapi.cr b/src/ipapi.cr index 73a331b..2e8a800 100644 --- a/src/ipapi.cr +++ b/src/ipapi.cr @@ -35,19 +35,10 @@ module Ipapi def initialize(@api_key : String? = nil) end - # Location of a specific IP - def locate(ip_address : String) : Location? - url = "#{API_URL}#{ip_address}/json" - url = url + "?key=#{@api_key}" if @api_key - - response = HTTP::Client.get(url) - - parse_locate_response(response) - end - - # Location of client’s IP - def locate : Location? - url = "#{API_URL}json" + # Retrive the location of a specific IP address. + # If `ip_address` is `nil`, use the client's IP. + def locate(ip_address : String? = nil) : Location? + url = Path.new([API_URL, ip_address, "json"].compact).to_s url = url + "?key=#{@api_key}" if @api_key response = HTTP::Client.get(url) @@ -56,19 +47,11 @@ module Ipapi end {% for field, description in FIELDS %} - # Retrive {{description.id}} for an IP address - def {{field.id}}(ip_address : String) : String - url = "#{API_URL}#{ip_address}/{{field.id}}" - url = url + "?key=#{@api_key}" if @api_key - - response = HTTP::Client.get(url) - - parse_field_response(response) - end + # Retrive {{description.id}} of a specific IP address. + # If `ip_address` is `nil`, use the client's IP. + def {{field.id}}(ip_address : String? = nil) : String + url = Path.new([API_URL, ip_address, "{{field.id}}"].compact).to_s - # Retrive {{description.id}} - def {{field.id}} : String - url = "#{API_URL}{{field.id}}" url = url + "?key=#{@api_key}" if @api_key response = HTTP::Client.get(url)