środa, 24 sierpnia 2016

Extract method refactor and passing &block

Today I've tried to refactor code by extracting some part to a method. Spuriously it didn't work.

############################# first version
def generate
@volunteers.includes(
[:user, { taggings: :tag }]
).find_each(batch_size: 1000) do |volunteer|
csv << VolunteerPresenter.new(volunteer).to_csv
end
end
############################ second version not working
def generate
prefetch_volunteers do |volunteer|
csv << VolunteerPresenter.new(volunteer).to_csv
end
end
private
def prefetch_volunteers
@volunteers.includes(
[:user, { taggings: :tag }]
).find_each(batch_size: 1000)
end
view raw report.rb hosted with ❤ by GitHub
Problem was with passing block to a method. when you do that you pass block to method not the results.
In order to fix it we need to pass a block to find_each method by using &Proc.new as an extra argument. According to this article it is a fastest method.

def generate
prefetch_volunteers do |volunteer|
csv << VolunteerPresenter.new(volunteer).to_csv
end
end
private
def prefetch_volunteers
@volunteers.includes(
[:user, { taggings: :tag }]
).find_each(batch_size: 1000, &Proc.new)
end
view raw report.rb hosted with ❤ by GitHub

Brak komentarzy:

Prześlij komentarz