taiwan_city.rb 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. require "taiwan_city/engine"
  2. module TaiwanCity
  3. TAIWAN = '00000' # 全国
  4. PATTERN = /(\d{2})(\d{3})(\d?)/
  5. class << self
  6. def list(parent_id = '00000')
  7. result = []
  8. return result if parent_id.blank?
  9. city_id = city(parent_id)
  10. children = data
  11. children = children[city_id][:children] if children.has_key?(city_id)
  12. children.each_key do |id|
  13. result.push [ children[id][:text], id]
  14. end
  15. #sort
  16. # result.sort! {|a, b| a[1] <=> b[1]}
  17. result
  18. end
  19. # @options[:prepend_parent] 是否显示上级区域
  20. def get(id, options = {})
  21. return '' if id.blank?
  22. prepend_parent = options[:prepend_parent] || false
  23. children = data
  24. return children[id][:text] if children.has_key?(id)
  25. city_id = city(id)
  26. city_text = children[city_id][:text]
  27. children = children[city_id][:children]
  28. return "#{prepend_parent ? (city_text) : ''}#{children[id][:text]}"
  29. end
  30. def city(code)
  31. match(code)[1].ljust(5, '0')
  32. end
  33. def get_info_from_address(address)
  34. return '' if address.blank?
  35. address.gsub!('臺', '台')
  36. addr = {}
  37. data.each do |city_code, city|
  38. next if address.exclude?(city[:text])
  39. addr[:city] = city[:text]
  40. addr[:city_code] = city_code
  41. city[:children].each do |dist_code, dist|
  42. next if address.exclude?(dist[:text])
  43. addr[:dist] = dist[:text]
  44. addr[:dist_code] = dist_code
  45. addr[:post_code] = dist_code[2..5]
  46. break
  47. end
  48. break
  49. end
  50. addr[:address] = address.gsub(addr[:city], '').gsub(addr[:dist], '')
  51. addr[:full_address] = address
  52. addr
  53. end
  54. private
  55. def data
  56. unless @list
  57. #{ '440000' =>
  58. # {
  59. # :text => '广东',
  60. # :children =>
  61. # {
  62. # '440300' =>
  63. # {
  64. # :text => '深圳',
  65. # :children =>
  66. # {
  67. # '440305' => { :text => '南山' }
  68. # }
  69. # }
  70. # }
  71. # }
  72. # }
  73. @list = {}
  74. #@see: http://github.com/RobinQu/LocationSelect-Plugin/raw/master/areas_1.0.json
  75. json = JSON.parse(File.read("#{Engine.root}/db/areas.json"))
  76. districts = json.values.flatten
  77. districts.each do |district|
  78. id = district['id']
  79. text = district['text']
  80. if id.end_with?('000')
  81. @list[id] = {:text => text, :children => {}}
  82. else
  83. city_id = city(id)
  84. @list[city_id] = {:text => text, :children => {}} unless @list.has_key?(city_id)
  85. @list[city_id][:children][id] = {:text => text}
  86. end
  87. end
  88. end
  89. @list
  90. end
  91. def match(code)
  92. code.match(PATTERN)
  93. end
  94. end
  95. end