See He.re! - code collaboration pastebin See He.re! BestNa.me - The Best Name for Your Needs

Paste search
Recent pastes
Forgot password?
ip_locator.rb
  1. ##
  2. # Copyright (c) 2014, BestNa.me.
  3. # All Rights Reserved.
  4. ##
  5.  
  6. ##
  7. # Written as a fix for tr.im (IPLocator class is missing in the original source).
  8. ##
  9.  
  10. ##
  11. # Tr.im's Copyright (c): The Nambu Network Inc.
  12. #
  13. # Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation
  14. # files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy,
  15. # modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software
  16. # is furnished to do so, subject to the following conditions:
  17. #
  18. # The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
  19. #
  20. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
  21. # OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  22. # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
  23. # IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  24. ##
  25. require 'location_system'
  26.  
  27. class IPLocator
  28.   include LocationSystem
  29.  
  30.   attr_accessor :country_id, :region_id, :city_id, :country
  31.  
  32.   def initialize(params = {})
  33.     @ip_address = params[:ip_address]
  34.     ip_num = ip_to_ipnum(@ip_address);
  35.     qs = "SELECT `countries`.id AS country_id FROM `countries` "
  36.     qs << "INNER JOIN `ip_countries` ON `countries`.code = `ip_countries`.country_code "
  37.     qs << "WHERE ( #{ip_num} >= `ip_countries`.ip_from AND `ip_countries`.ip_to >= #{ip_num})"
  38.     result = ActiveRecord::Base.connection.select_rows(qs)
  39.     if result.length > 1
  40.       RAILS_DEFAULT_LOGGER.info "AMBIGUOUS IP<->COUNTRY MAPPING: #{result.length} results found. That is, #{@ip_address} belongs to e.g. #{result[0][0]} as well as to #{result[1][0]}"
  41.     end
  42.     if result.blank?
  43.       @country_id = 255 # unknown country
  44.       RAILS_DEFAULT_LOGGER.info "COUNTRY FOR IP IS UNKNOWN"
  45.     else
  46.       @country_id = result[0][0].to_i
  47.       @country = TrimCountry.new
  48.       @country.id = @country_id
  49.       @country.code = result[0][1]
  50.       @country.name = result[0][2]
  51.     end
  52.     @region_id = 1
  53.     @city_id = 1
  54.   end
  55.  
  56. end
Parsed in 0.029 seconds