Skip to content

Commit 2d71a68

Browse files
committed
ActiveRecord & ruby optimizations
- select(:foo).map(:foo) -> pluck(:foo) - select(:foo).collect(:foo) -> pluck(:foo) - map { |foo| foo.bar } -> map(&:bar) - map { … }.flatten -> flat_map { … } - collect { … }.flatten -> flat_map { … } - gsub() -> sub() - gsub() -> tr()
1 parent 30c39fa commit 2d71a68

21 files changed

+46
-46
lines changed

app/controllers/networks_controller.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -78,7 +78,7 @@ def tag
7878
@topics = tags_array
7979
@topic = tags_array.join(' + ')
8080
@topic_user = nil
81-
@networks = tags_array.map { |tag| Network.networks_for_tag(tag) }.flatten.uniq if @networks.nil?
81+
@networks = tags_array.flat_map { |tag| Network.networks_for_tag(tag) }.uniq if @networks.nil?
8282
end
8383

8484
def mayor

app/controllers/opportunities_controller.rb

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -88,7 +88,7 @@ def index
8888

8989
chosen_location = 'Worldwide' if chosen_location.nil?
9090
@locations = Rails.cache.fetch("job_locations_#{params[:location]}_#{params[:skill]}", expires_in: 1.hour) do
91-
Opportunity.by_tag(tag).map(&:locations).flatten.reject { |loc| loc == "Worldwide" }.push("Worldwide").uniq.compact
91+
Opportunity.by_tag(tag).flat_map(&:locations).reject { |loc| loc == "Worldwide" }.push("Worldwide").uniq.compact
9292
end
9393
@locations.delete(chosen_location) unless @locations.frozen?
9494
params[:location] = chosen_location
@@ -147,11 +147,11 @@ def stringify_location
147147
end
148148

149149
def all_job_locations
150-
Rails.cache.fetch('job_locations', expires_in: 23.hours) { Opportunity.all.map(&:locations).flatten.push("Worldwide").uniq.compact }
150+
Rails.cache.fetch('job_locations', expires_in: 23.hours) { Opportunity.all.flat_map(&:locations).push("Worldwide").uniq.compact }
151151
end
152152

153153
def all_job_skills
154-
Rails.cache.fetch('job_skills', expires_in: 23.hours) { Opportunity.all.map(&:tags).flatten.uniq.compact }
154+
Rails.cache.fetch('job_skills', expires_in: 23.hours) { Opportunity.all.flat_map(&:tags).uniq.compact }
155155
end
156156

157157
def closest_to_user(user)

app/controllers/protips_controller.rb

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -525,7 +525,7 @@ def suggested_networks
525525
@protips.facets['suggested-networks']['terms'].map { |h| h['term'] }
526526
else
527527
#gets top 10 tags for the protips and picks up associated networks
528-
Network.tagged_with(@protips.map(&:tags).flatten.reduce(Hash.new(0)) { |h, t| h[t] += 1; h }.sort_by { |k, v| -v }.first(10).flatten.values_at(*(0..20).step(2))).select(:slug).limit(4).map(&:slug)
528+
Network.tagged_with(@protips.flat_map(&:tags).reduce(Hash.new(0)) { |h, t| h[t] += 1; h }.sort_by { |k, v| -v }.first(10).flatten.values_at(*(0..20).step(2))).limit(4).pluck(:slug)
529529
end
530530
end
531531
@@ -545,7 +545,7 @@ def get_topics_from_protips(protips)
545545
topics = protips.facets['top-tags']['terms'].map { |h| h['term'] }
546546
end
547547
548-
topics = protips.map(&:tags).flatten.uniq.first(8) if topics.blank? && protips.present?
548+
topics = protips.flat_map(&:tags).uniq.first(8) if topics.blank? && protips.present?
549549
topics
550550
end
551551

app/controllers/teams_controller.rb

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -290,7 +290,7 @@ def team_from_params(opts)
290290
end
291291

292292
def replace_section(section_name)
293-
section_name = section_name.gsub('-', '_')
293+
section_name = section_name.tr('-', '_')
294294
"$('##{section_name}').replaceWith('#{escape_javascript(render(:partial => section_name))}');"
295295
end
296296

@@ -313,7 +313,7 @@ def page_based_on_rank(rank)
313313

314314
def job_public_ids
315315
Opportunity
316-
Rails.cache.fetch('all-jobs-public-ids', :expires_in => 1.hour) { Opportunity.select(:public_id).group('team_id, created_at, public_id').map(&:public_id) }
316+
Rails.cache.fetch('all-jobs-public-ids', :expires_in => 1.hour) { Opportunity.group('team_id, created_at, public_id').pluck(:public_id) }
317317
end
318318

319319
def next_job(job)

app/helpers/badges_helper.rb

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ def share_coderwall_on_twitter
88
end
99

1010
def dom_tag(tag)
11-
sanitize_dom_id(tag).gsub(' ', '-').gsub('+', 'plus').gsub('#', 'sharp')
11+
sanitize_dom_id(tag).tr(' ', '-').gsub('+', 'plus').gsub('#', 'sharp')
1212
end
1313

1414
def dom_for_badge(badge)
@@ -27,4 +27,4 @@ def unlocked_badge_title
2727
"#{@user.short_name} leveled up and unlocked the #{@badge.display_name} on Coderwall"
2828
end
2929

30-
end
30+
end

app/helpers/premium_helper.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -70,7 +70,7 @@ def panel_form_for_section(section_id, title = nil, show_save_button = true, &bl
7070
end
7171

7272
def partialify_html_section_id(section_id)
73-
section_id.to_s.gsub("-", "_").gsub('#', '')
73+
section_id.to_s.tr("-", "_").gsub('#', '')
7474
end
7575

7676
def add_active_class_to_first_member

app/helpers/protips_helper.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -285,7 +285,7 @@ def display_scope_class
285285
end
286286

287287
def current_user_upvotes
288-
@upvoted_protip_ids ||= current_user.upvoted_protips.select(:public_id).map(&:public_id)
288+
@upvoted_protip_ids ||= current_user.upvoted_protips.pluck(:public_id)
289289
end
290290

291291
def user_upvoted?(protip)

app/jobs/create_network_job.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ class CreateNetworkJob
55

66
def perform(tag)
77
top_tags = Protip.trending_topics
8-
sub_tags = Protip.tagged_with([tag], on: :topics).collect(&:topics).flatten
8+
sub_tags = Protip.tagged_with([tag], on: :topics).flat_map(&:topics)
99
sub_tags.delete_if { |sub_tag| top_tags.include? sub_tag }
1010
unless sub_tags.blank?
1111
sub_tag_frequency = sub_tags.inject(Hash.new(0)) { |h, sub_tag| h[sub_tag] += 1; h }

app/models/badges/node_knockout.rb

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -115,7 +115,7 @@ def github_for(path)
115115
begin
116116
res = Servant.get("http://nodeknockout.com#{path}")
117117
doc = Nokogiri::HTML(res.to_s)
118-
username = doc.css("a.github").first[:href].gsub(/https?:\/\/github.com\//, '')
118+
username = doc.css("a.github").first[:href].sub(/https?:\/\/github.com\//, '')
119119
role = doc.css(".role").first.text
120120
Rails.logger.info "Found node knockout #{role}: #{username}" if ENV['DEBUG']
121121
return [role, username]
@@ -129,7 +129,7 @@ def twitter_for(path)
129129
begin
130130
res = Servant.get("http://nodeknockout.com#{path}")
131131
doc = Nokogiri::HTML(res.to_s)
132-
username = doc.css("a.twitter").first[:href].gsub("http://twitter.com/", '').strip
132+
username = doc.css("a.twitter").first[:href].sub("http://twitter.com/", '').strip
133133
role = doc.css(".role").first.text
134134
Rails.logger.info "Found node knockout #{role}: #{username}"
135135
return [role, username]

app/models/badges/polygamous.rb

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -9,14 +9,14 @@ class Polygamous < BadgeBase
99
def reasons
1010
@reasons ||= begin
1111
facts = user.facts.select { |fact| fact.tagged?('personal', 'repo', 'original') }
12-
facts.collect do |fact|
12+
facts.flat_map do |fact|
1313
fact.metadata[:languages]
14-
end.flatten.uniq
14+
end.uniq
1515
end
1616
end
1717

1818
def award?
1919
reasons.size >= 4
2020
end
2121

22-
end
22+
end

app/models/blog_post.rb

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@ def all_entries
4545
end
4646

4747
def id_of(pathname)
48-
pathname.basename.to_s.gsub(pathname.extname, "")
48+
pathname.basename.to_s.sub(pathname.extname, "")
4949
end
5050
end
5151

@@ -83,4 +83,4 @@ def cached_content
8383
@cached_content ||= @content.read.split("---")
8484
end
8585

86-
end
86+
end

app/models/concerns/team_analytics.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,7 @@ def number_of_completed_sections(*excluded_sections)
6767
completed_sections = 0
6868

6969
sections = (SECTIONS - excluded_sections).map do |section|
70-
"has_#{section.gsub(/-/, '_')}?"
70+
"has_#{section.tr('-', '_')}?"
7171
end
7272
sections.each do |section_complete|
7373
completed_sections += 1 if self.respond_to?(section_complete) &&

app/models/concerns/user_oauth.rb

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -94,8 +94,8 @@ def avatar_url_for(oauth)
9494
end
9595

9696
def all_tokens
97-
with_tokens.select("github_token").collect(&:github_token)
97+
with_tokens.pluck(:github_token)
9898
end
9999

100100
end
101-
end
101+
end

app/models/github_old.rb

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -113,7 +113,7 @@ def repos_for(github_username, since=Time.at(0))
113113
end
114114

115115
def predominant_repo_lanugage_for_link(link)
116-
owner, repo_name = *link.gsub(/https?:\/\/github.com\//i, '').split('/')
116+
owner, repo_name = *link.sub(/https?:\/\/github.com\//i, '').split('/')
117117
repo(owner, repo_name)[:language]
118118
end
119119

@@ -181,4 +181,4 @@ def repo_forks(owner, name, since=Time.at(0))
181181
rescue Errno::ECONNREFUSED => e
182182
retry
183183
end
184-
end
184+
end

app/models/lanyrd.rb

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ class Lanyrd < Struct.new(:username)
55

66
def facts
77
events.collect do |event|
8-
id = event[:url].gsub(HOST, '') + ":#{username}"
8+
id = event[:url].sub(HOST, '') + ":#{username}"
99
Fact.append!(id, "lanyrd:#{username}", event[:name], event[:date], event[:url], event[:tags])
1010
end
1111
end
@@ -38,4 +38,4 @@ def profile
3838
{}
3939
end
4040
end
41-
end
41+
end

app/models/network.rb

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -40,12 +40,12 @@ def slugify(name)
4040
if !!(name =~ /\p{Latin}/)
4141
name.to_s.downcase.gsub(/[^a-z0-9]+/i, '-').chomp('-')
4242
else
43-
name.to_s.gsub(/\s/, "-")
43+
name.to_s.tr(' ', '-')
4444
end
4545
end
4646

4747
def unslugify(slug)
48-
slug.gsub(/\-/, ' ')
48+
slug.tr('-', ' ')
4949
end
5050

5151
def all_with_tag(tag_name)
@@ -201,12 +201,12 @@ def expert_protips(limit=nil, offset =0)
201201
end
202202

203203
def members(limit = -1, offset = 0)
204-
members_scope = User.where(id: Follow.for_followable(self).select(:follower_id)).offset(offset)
204+
members_scope = User.where(id: Follow.for_followable(self).pluck(:follower_id)).offset(offset)
205205
limit > 0 ? members_scope.limit(limit) : members_scope
206206
end
207207

208208
def new_members(limit = nil, offset = 0)
209-
User.where(id: Follow.for_followable(self).select(:follower_id).where('follows.created_at > ?', 1.week.ago)).limit(limit).offset(offset)
209+
User.where(id: Follow.for_followable(self).where('follows.created_at > ?', 1.week.ago).pluck(:follower_id)).limit(limit).offset(offset)
210210
end
211211

212212
def ranked_members(limit = 15)

app/models/protip.rb

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -121,7 +121,7 @@ def trending_topics
121121

122122
unless trending_protips.respond_to?(:errored?) and trending_protips.errored?
123123
static_trending = ENV['FEATURED_TOPICS'].split(",").map(&:strip).map(&:downcase) unless ENV['FEATURED_TOPICS'].blank?
124-
dynamic_trending = trending_protips.map { |p| p.tags }.flatten.reduce(Hash.new(0)) { |h, tag| h.tap { |h| h[tag] += 1 } }.sort { |a1, a2| a2[1] <=> a1[1] }.map { |entry| entry[0] }.reject { |tag| User.where(username: tag).any? }
124+
dynamic_trending = trending_protips.flat_map { |p| p.tags }.reduce(Hash.new(0)) { |h, tag| h.tap { |h| h[tag] += 1 } }.sort { |a1, a2| a2[1] <=> a1[1] }.map { |entry| entry[0] }.reject { |tag| User.where(username: tag).any? }
125125
((static_trending || []) + dynamic_trending).uniq
126126
else
127127
Tag.last(20).map(&:name).reject { |name| User.exists?(username: name) }
@@ -234,7 +234,7 @@ def search_trending_by_team(team_id, query_string, page, per_page)
234234
Protip.search(query, [], page: page, per_page: per_page)
235235
rescue Errno::ECONNREFUSED
236236
team = Team.where(slug: team_id).first
237-
team.members.collect(&:protips).flatten
237+
team.members.flat_map(&:protips)
238238
end
239239

240240
def search_trending_by_user(username, query_string, tags, page, per_page)
@@ -259,7 +259,7 @@ def search_bookmarked_protips(username, page, per_page)
259259
end
260260

261261
def most_interesting_for(user, since=Time.at(0), page = 1, per_page = 10)
262-
search_top_trending_since("only_link:false", since, user.networks.map(&:ordered_tags).flatten.concat(user.skills.map(&:name)), page, per_page)
262+
search_top_trending_since("only_link:false", since, user.networks.flat_map(&:ordered_tags).concat(user.skills.map(&:name)), page, per_page)
263263
end
264264

265265
def search_top_trending_since(query, since, tags, page = 1, per_page = 10)

app/models/team.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -112,7 +112,7 @@ def self.slugify(name)
112112
if !!(name =~ /\p{Latin}/)
113113
name.to_s.downcase.gsub(/[^a-z0-9]+/i, '-').chomp('-')
114114
else
115-
name.to_s.gsub(/\s/, "-")
115+
name.to_s.tr(' ', '-')
116116
end
117117
end
118118

app/models/teams/account.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -118,7 +118,7 @@ def suspend!
118118
team.monthly_subscription = false
119119
team.valid_jobs = false
120120
team.save
121-
team.jobs.map { |job| job.deactivate! }
121+
team.jobs.map(&:deactivate!)
122122
end
123123

124124
def add_analytics

app/models/user.rb

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -386,7 +386,7 @@ def deleted_skill?(skill_name)
386386

387387

388388
def tokenized_lanyrd_tags
389-
lanyrd_facts.collect { |fact| fact.tags }.flatten.compact.map { |tag| Skill.tokenize(tag) }
389+
lanyrd_facts.flat_map { |fact| fact.tags }.compact.map { |tag| Skill.tokenize(tag) }
390390
end
391391

392392
def last_modified_at
@@ -426,11 +426,11 @@ def activity_stats(since=Time.at(0), full=false)
426426
end
427427

428428
def upvoted_protips
429-
Protip.where(id: Like.where(likable_type: "Protip").where(user_id: self.id).select(:likable_id).map(&:likable_id))
429+
Protip.where(id: Like.where(likable_type: "Protip").where(user_id: self.id).pluck(:likable_id))
430430
end
431431

432432
def upvoted_protips_public_ids
433-
upvoted_protips.select(:public_id).map(&:public_id)
433+
upvoted_protips.pluck(:public_id)
434434
end
435435

436436
def followers_since(since=Time.at(0))
@@ -457,7 +457,7 @@ def score
457457
end
458458

459459
def team_member_ids
460-
User.select(:id).where(team_id: self.team_id.to_s).map(&:id)
460+
User.where(team_id: self.team_id.to_s).pluck(:id)
461461
end
462462

463463
def penalize!(amount=(((team && team.members.size) || 6) / 6.0)*activitiy_multipler)
@@ -677,19 +677,19 @@ def member_of?(network)
677677
end
678678

679679
def following_users_ids
680-
self.following_users.select(:id).map(&:id)
680+
self.following_users.pluck(:id)
681681
end
682682

683683
def following_teams_ids
684-
self.followed_teams.map(&:team_id)
684+
self.followed_teams.pluck(:team_id)
685685
end
686686

687687
def following_team_members_ids
688-
User.select(:id).where(team_id: self.following_teams_ids).map(&:id)
688+
User.where(team_id: self.following_teams_ids).pluck(:id)
689689
end
690690

691691
def following_networks_ids
692-
self.following_networks.select(:id).map(&:id)
692+
self.following_networks.pluck(:id)
693693
end
694694

695695
def following_networks_tags
@@ -723,7 +723,7 @@ def is_mayor_of?(network)
723723
end
724724

725725
def networks_based_on_skills
726-
self.skills.collect { |skill| Network.all_with_tag(skill.name) }.flatten.uniq
726+
self.skills.flat_map { |skill| Network.all_with_tag(skill.name) }.uniq
727727
end
728728

729729
def visited!

app/models/users/github/followed_repo.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ def description
1212
end
1313

1414
def repo
15-
data['link'].gsub('https://github.com/', '')
15+
data['link'].sub('https://github.com/', '')
1616
end
1717

1818
def date

0 commit comments

Comments
 (0)