taiwan_city.rb 2.2 KB

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