Skip to content

ActiveRecord & ruby optimizations #255

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Dec 3, 2014
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion app/controllers/networks_controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ def tag
@topics = tags_array
@topic = tags_array.join(' + ')
@topic_user = nil
@networks = tags_array.map { |tag| Network.networks_for_tag(tag) }.flatten.uniq if @networks.nil?
@networks = tags_array.flat_map { |tag| Network.networks_for_tag(tag) }.uniq if @networks.nil?
end

def mayor
Expand Down
6 changes: 3 additions & 3 deletions app/controllers/opportunities_controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ def index

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

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

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

def closest_to_user(user)
Expand Down
4 changes: 2 additions & 2 deletions app/controllers/protips_controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -525,7 +525,7 @@ def suggested_networks
@protips.facets['suggested-networks']['terms'].map { |h| h['term'] }
else
#gets top 10 tags for the protips and picks up associated networks
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)
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)
end
end

Expand All @@ -545,7 +545,7 @@ def get_topics_from_protips(protips)
topics = protips.facets['top-tags']['terms'].map { |h| h['term'] }
end

topics = protips.map(&:tags).flatten.uniq.first(8) if topics.blank? && protips.present?
topics = protips.flat_map(&:tags).uniq.first(8) if topics.blank? && protips.present?
topics
end

Expand Down
4 changes: 2 additions & 2 deletions app/controllers/teams_controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -290,7 +290,7 @@ def team_from_params(opts)
end

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

Expand All @@ -313,7 +313,7 @@ def page_based_on_rank(rank)

def job_public_ids
Opportunity
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) }
Rails.cache.fetch('all-jobs-public-ids', :expires_in => 1.hour) { Opportunity.group('team_id, created_at, public_id').pluck(:public_id) }
end

def next_job(job)
Expand Down
4 changes: 2 additions & 2 deletions app/helpers/badges_helper.rb
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ def share_coderwall_on_twitter
end

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

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

end
end
2 changes: 1 addition & 1 deletion app/helpers/premium_helper.rb
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ def panel_form_for_section(section_id, title = nil, show_save_button = true, &bl
end

def partialify_html_section_id(section_id)
section_id.to_s.gsub("-", "_").gsub('#', '')
section_id.to_s.tr("-", "_").gsub('#', '')
end

def add_active_class_to_first_member
Expand Down
2 changes: 1 addition & 1 deletion app/helpers/protips_helper.rb
Original file line number Diff line number Diff line change
Expand Up @@ -285,7 +285,7 @@ def display_scope_class
end

def current_user_upvotes
@upvoted_protip_ids ||= current_user.upvoted_protips.select(:public_id).map(&:public_id)
@upvoted_protip_ids ||= current_user.upvoted_protips.pluck(:public_id)
end

def user_upvoted?(protip)
Expand Down
2 changes: 1 addition & 1 deletion app/jobs/create_network_job.rb
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ class CreateNetworkJob

def perform(tag)
top_tags = Protip.trending_topics
sub_tags = Protip.tagged_with([tag], on: :topics).collect(&:topics).flatten
sub_tags = Protip.tagged_with([tag], on: :topics).flat_map(&:topics)
sub_tags.delete_if { |sub_tag| top_tags.include? sub_tag }
unless sub_tags.blank?
sub_tag_frequency = sub_tags.inject(Hash.new(0)) { |h, sub_tag| h[sub_tag] += 1; h }
Expand Down
4 changes: 2 additions & 2 deletions app/models/badges/node_knockout.rb
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ def github_for(path)
begin
res = Servant.get("http://nodeknockout.com#{path}")
doc = Nokogiri::HTML(res.to_s)
username = doc.css("a.github").first[:href].gsub(/https?:\/\/github.com\//, '')
username = doc.css("a.github").first[:href].sub(/https?:\/\/github.com\//, '')
role = doc.css(".role").first.text
Rails.logger.info "Found node knockout #{role}: #{username}" if ENV['DEBUG']
return [role, username]
Expand All @@ -129,7 +129,7 @@ def twitter_for(path)
begin
res = Servant.get("http://nodeknockout.com#{path}")
doc = Nokogiri::HTML(res.to_s)
username = doc.css("a.twitter").first[:href].gsub("http://twitter.com/", '').strip
username = doc.css("a.twitter").first[:href].sub("http://twitter.com/", '').strip
role = doc.css(".role").first.text
Rails.logger.info "Found node knockout #{role}: #{username}"
return [role, username]
Expand Down
6 changes: 3 additions & 3 deletions app/models/badges/polygamous.rb
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,14 @@ class Polygamous < BadgeBase
def reasons
@reasons ||= begin
facts = user.facts.select { |fact| fact.tagged?('personal', 'repo', 'original') }
facts.collect do |fact|
facts.flat_map do |fact|
fact.metadata[:languages]
end.flatten.uniq
end.uniq
end
end

def award?
reasons.size >= 4
end

end
end
4 changes: 2 additions & 2 deletions app/models/blog_post.rb
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ def all_entries
end

def id_of(pathname)
pathname.basename.to_s.gsub(pathname.extname, "")
pathname.basename.to_s.sub(pathname.extname, "")
end
end

Expand Down Expand Up @@ -83,4 +83,4 @@ def cached_content
@cached_content ||= @content.read.split("---")
end

end
end
2 changes: 1 addition & 1 deletion app/models/concerns/team_analytics.rb
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ def number_of_completed_sections(*excluded_sections)
completed_sections = 0

sections = (SECTIONS - excluded_sections).map do |section|
"has_#{section.gsub(/-/, '_')}?"
"has_#{section.tr('-', '_')}?"
end
sections.each do |section_complete|
completed_sections += 1 if self.respond_to?(section_complete) &&
Expand Down
4 changes: 2 additions & 2 deletions app/models/concerns/user_oauth.rb
Original file line number Diff line number Diff line change
Expand Up @@ -94,8 +94,8 @@ def avatar_url_for(oauth)
end

def all_tokens
with_tokens.select("github_token").collect(&:github_token)
with_tokens.pluck(:github_token)
end

end
end
end
4 changes: 2 additions & 2 deletions app/models/github_old.rb
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ def repos_for(github_username, since=Time.at(0))
end

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

Expand Down Expand Up @@ -181,4 +181,4 @@ def repo_forks(owner, name, since=Time.at(0))
rescue Errno::ECONNREFUSED => e
retry
end
end
end
4 changes: 2 additions & 2 deletions app/models/lanyrd.rb
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ class Lanyrd < Struct.new(:username)

def facts
events.collect do |event|
id = event[:url].gsub(HOST, '') + ":#{username}"
id = event[:url].sub(HOST, '') + ":#{username}"
Fact.append!(id, "lanyrd:#{username}", event[:name], event[:date], event[:url], event[:tags])
end
end
Expand Down Expand Up @@ -38,4 +38,4 @@ def profile
{}
end
end
end
end
8 changes: 4 additions & 4 deletions app/models/network.rb
Original file line number Diff line number Diff line change
Expand Up @@ -40,12 +40,12 @@ def slugify(name)
if !!(name =~ /\p{Latin}/)
name.to_s.downcase.gsub(/[^a-z0-9]+/i, '-').chomp('-')
else
name.to_s.gsub(/\s/, "-")
name.to_s.tr(' ', '-')
end
end

def unslugify(slug)
slug.gsub(/\-/, ' ')
slug.tr('-', ' ')
end

def all_with_tag(tag_name)
Expand Down Expand Up @@ -201,12 +201,12 @@ def expert_protips(limit=nil, offset =0)
end

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

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

def ranked_members(limit = 15)
Expand Down
6 changes: 3 additions & 3 deletions app/models/protip.rb
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,7 @@ def trending_topics

unless trending_protips.respond_to?(:errored?) and trending_protips.errored?
static_trending = ENV['FEATURED_TOPICS'].split(",").map(&:strip).map(&:downcase) unless ENV['FEATURED_TOPICS'].blank?
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? }
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? }
((static_trending || []) + dynamic_trending).uniq
else
Tag.last(20).map(&:name).reject { |name| User.exists?(username: name) }
Expand Down Expand Up @@ -234,7 +234,7 @@ def search_trending_by_team(team_id, query_string, page, per_page)
Protip.search(query, [], page: page, per_page: per_page)
rescue Errno::ECONNREFUSED
team = Team.where(slug: team_id).first
team.members.collect(&:protips).flatten
team.members.flat_map(&:protips)
end

def search_trending_by_user(username, query_string, tags, page, per_page)
Expand All @@ -259,7 +259,7 @@ def search_bookmarked_protips(username, page, per_page)
end

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

def search_top_trending_since(query, since, tags, page = 1, per_page = 10)
Expand Down
2 changes: 1 addition & 1 deletion app/models/team.rb
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@ def self.slugify(name)
if !!(name =~ /\p{Latin}/)
name.to_s.downcase.gsub(/[^a-z0-9]+/i, '-').chomp('-')
else
name.to_s.gsub(/\s/, "-")
name.to_s.tr(' ', '-')
end
end

Expand Down
2 changes: 1 addition & 1 deletion app/models/teams/account.rb
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,7 @@ def suspend!
team.monthly_subscription = false
team.valid_jobs = false
team.save
team.jobs.map { |job| job.deactivate! }
team.jobs.map(&:deactivate!)
end

def add_analytics
Expand Down
18 changes: 9 additions & 9 deletions app/models/user.rb
Original file line number Diff line number Diff line change
Expand Up @@ -386,7 +386,7 @@ def deleted_skill?(skill_name)


def tokenized_lanyrd_tags
lanyrd_facts.collect { |fact| fact.tags }.flatten.compact.map { |tag| Skill.tokenize(tag) }
lanyrd_facts.flat_map { |fact| fact.tags }.compact.map { |tag| Skill.tokenize(tag) }
end

def last_modified_at
Expand Down Expand Up @@ -426,11 +426,11 @@ def activity_stats(since=Time.at(0), full=false)
end

def upvoted_protips
Protip.where(id: Like.where(likable_type: "Protip").where(user_id: self.id).select(:likable_id).map(&:likable_id))
Protip.where(id: Like.where(likable_type: "Protip").where(user_id: self.id).pluck(:likable_id))
end

def upvoted_protips_public_ids
upvoted_protips.select(:public_id).map(&:public_id)
upvoted_protips.pluck(:public_id)
end

def followers_since(since=Time.at(0))
Expand All @@ -457,7 +457,7 @@ def score
end

def team_member_ids
User.select(:id).where(team_id: self.team_id.to_s).map(&:id)
User.where(team_id: self.team_id.to_s).pluck(:id)
end

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

def following_users_ids
self.following_users.select(:id).map(&:id)
self.following_users.pluck(:id)
end

def following_teams_ids
self.followed_teams.map(&:team_id)
self.followed_teams.pluck(:team_id)
end

def following_team_members_ids
User.select(:id).where(team_id: self.following_teams_ids).map(&:id)
User.where(team_id: self.following_teams_ids).pluck(:id)
end

def following_networks_ids
self.following_networks.select(:id).map(&:id)
self.following_networks.pluck(:id)
end

def following_networks_tags
Expand Down Expand Up @@ -723,7 +723,7 @@ def is_mayor_of?(network)
end

def networks_based_on_skills
self.skills.collect { |skill| Network.all_with_tag(skill.name) }.flatten.uniq
self.skills.flat_map { |skill| Network.all_with_tag(skill.name) }.uniq
end

def visited!
Expand Down
2 changes: 1 addition & 1 deletion app/models/users/github/followed_repo.rb
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ def description
end

def repo
data['link'].gsub('https://github.com/', '')
data['link'].sub('https://github.com/', '')
end

def date
Expand Down