Last active
January 2, 2016 04:29
-
-
Save mimosa/8250737 to your computer and use it in GitHub Desktop.
按城市导出用户联系信息。
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- encoding: utf-8 -*- | |
require 'csv' | |
cities = {} | |
# 有联系方式的用户 | |
users = User.any_of(:mobile.ne =>nil, :email.ne => nil).desc(:rank).only(:nickname, :name, :email, :mobile, :location) | |
# 指定城市 | |
keys = "北京、天津、石家庄、太原、呼和浩特、沈阳、大连、长春、哈尔滨、上海、南京、杭州、宁波、合肥、福州、厦门、南昌、济南、青岛、郑州、武汉、长沙、广州、深圳、南宁、海口、重庆、成都、贵阳、昆明、西安、兰州、西宁、银川、乌鲁木齐" | |
users = users.in( 'location.city' => keys.split('、') ) | |
# 构造 | |
users.each do |u| | |
if u.location? # 位置 | |
unless u.location.city.blank? # 城市 | |
cities[u.location.city] = [] unless cities.has_key?(u.location.city) | |
cities[u.location.city] << [ u.nickname, u.name, u.mobile, u.email ] | |
end | |
end | |
end | |
# TOP | |
limit = 10 # 限制 | |
# 导出 | |
CSV.open("./public/users.csv", "wb:GB18030", col_sep: ',') do |csv| | |
csv << ['城市', '昵称', '姓名', '手机', '邮件'] | |
cities.each do |city, users| | |
counter = 0 # 计数器 | |
users.each do |u| | |
csv << ([city] + u) | |
counter += 1 | |
break if limit > 0 && counter >= limit # 达到限制数后,跳出 | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment