Refactor methods that rely on instance variable
How can refactor these methods so that they don't rely on using an instance variable (@conference_facets)?
def count_conf_facets(events)
@conference_facets =开发者_Python百科 {}
for event in events do
home_team_conf = event.home_team_conf
away_team_conf = event.away_team_conf
increment_conf_facet(home_team_conf)
if home_team_conf.id != away_team_conf.id then
increment_conf_facet(away_team_conf)
end
end
end
def increment_conf_facet(conference)
if @conference_facets[conference.id].nil? then
@conference_facets[conference.id] = 0
end
@conference_facets[conference.id] += 1
end
If these facets are stored in a database, you can get the count right out of the database, which is much more efficient than looping through all the events, although you may have to play around with your group_by and join criteria, as well as your data modeling.
Anyway, to get rid of having to use an instance variable, you can move all of this logic into a single function, or play around with what you're passing between functions. For example
def count_conf_facets(events)
counts = {}
events.each do |event|
[event.home_team_conf.id, event.away_team_conf.id].uniq.each do |conf_id|
counts[conf_id] ||= 0
counts[conf_id] += 1
end
end
counts
end
精彩评论