I have a rake task called pull_orders
which calls methods of a RemoteDbConnector
class to do things like establish a connection to an external db, generate raw SQL queries, execute queries and store records in the local db.
While trying to test it, I stumbled upon this answer which got me thinking whether my design is flawed.
Should rake tasks really be one liners? If so, where should I put all these method calls, given that they need to be called in a particular sequence?
My task looks like this:
namespace :db do
desc 'finds and populates data from remote db'
task pull_orders: :environment do
...
columns = ...
table = ...
options = ...
column_mappings = ...
RemoteDbConnector.generate_query(...)
RemoteDbConnector.execute_query(...)
RemoteDbConnector.map_column_names(...)
Order.create(...) #creates records based on hash generated by RemoteDbConnector
...
end
end
Reasonable people will probably not enforce a strict rule of no more than one line per rake task, but it is definitely nicer to move large blocks of code out of .rake files into classes:
So,
require
the classes in the rake tasks that use them. (Don't configure your app to autoload lib; that would load unwanted code and its dependencies in your production application.)