Modify a method on the fly in Ruby
I'd say you're on the right track with you idea to extract a method.

While I can't fully replicate your code and its context, I think something like this should work:

task countries: setup do |task_name|
  rows = rows_from_file("system/#{task_name.to_s}", 2)
  process_rows(task_name, rows) do |row|
    { alpha2: row[0], name: row[1] }
  end
end

# ...

def import_rows(task_name, rows, &amp;block)
  klass = task_name.to_s.classify
  bar = RakeProgressbar.new(rows.length)
  info "» Importing #{task_name.to_s.humanize}"
  rows.each do |row|
    attrs = block.call(row)
    klass.new(attrs).save!
    bar.inc
  end
  bar.finished
end


But it's going pretty far in its assumptions - it's basing a lot off of the task name alone.

A somewhat less fragile approach might be this where the correct class is explicitly passed to the helper method and the file name isn't guessed from the task name

task countries: setup do
  rows = rows_from_file("system/countries", 2)
  process_rows(Country, rows) do |row|
    { alpha2: row[0], name: row[1] }
  end
end

# ...

def import_rows(klass, rows, &amp;block)
  bar = RakeProgressbar.new(rows.length)
  info "» Importing #{klass.to_s.pluralize.humanize}"
  rows.each do |row|
    attrs = block.call(row)
    klass.new(attrs).save!
    bar.inc
  end
  bar.finished
end