taiwan_city.rb 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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. match(code)[1].ljust(5, '0')
  33. end
  34. private
  35. def data
  36. unless @list
  37. #{ '440000' =>
  38. # {
  39. # :text => '广东',
  40. # :children =>
  41. # {
  42. # '440300' =>
  43. # {
  44. # :text => '深圳',
  45. # :children =>
  46. # {
  47. # '440305' => { :text => '南山' }
  48. # }
  49. # }
  50. # }
  51. # }
  52. # }
  53. @list = {}
  54. #@see: http://github.com/RobinQu/LocationSelect-Plugin/raw/master/areas_1.0.json
  55. json = JSON.parse(File.read("#{Engine.root}/db/areas.json"))
  56. districts = json.values.flatten
  57. districts.each do |district|
  58. id = district['id']
  59. text = district['text']
  60. if id.end_with?('000')
  61. @list[id] = {:text => text, :children => {}}
  62. else
  63. city_id = city(id)
  64. @list[city_id] = {:text => text, :children => {}} unless @list.has_key?(city_id)
  65. @list[city_id][:children][id] = {:text => text}
  66. end
  67. end
  68. end
  69. @list
  70. end
  71. def match(code)
  72. code.match(PATTERN)
  73. end
  74. end
  75. end