Rake task help with DRYness

A

Alex Wayne

I'm somewhat new to writing my own rake tasks. I have a pair of tasks
that convert some stuff from one format to another.

rake my_ns:to_a
rake my_ns:to_b

And everything works just fine. The problem is that the implementation
the code is basically duplicated. The process is the same, the only
real difference is that old_format and new_format local variables are
swapped in the second conversion task. I want to make this much DRYer
by refactoring the common code out.

Now, if this was a ruby class, I would simply create a private method
called convert_to(format), or something similar. Then the format
conversion happens in this method, based on the argument.

How does one accomplish this with rake tasks? Basically I want to pass
arguments to a rake task, or method of some sort, and use the result. A
simple task in general programming, but I am not sure how to make this
work in the context of rake.

Thanks for the help.
 
J

Joel VanderWerf

Alex said:
I'm somewhat new to writing my own rake tasks. I have a pair of tasks
that convert some stuff from one format to another.

rake my_ns:to_a
rake my_ns:to_b

And everything works just fine. The problem is that the implementation
the code is basically duplicated. The process is the same, the only
real difference is that old_format and new_format local variables are
swapped in the second conversion task. I want to make this much DRYer
by refactoring the common code out.

Now, if this was a ruby class, I would simply create a private method
called convert_to(format), or something similar. Then the format
conversion happens in this method, based on the argument.

How does one accomplish this with rake tasks? Basically I want to pass
arguments to a rake task, or method of some sort, and use the result. A
simple task in general programming, but I am not sure how to make this
work in the context of rake.

Thanks for the help.

Not sure I understand, but why not just do what you said: define a
method that handles the common work?

task :to_a do |name|
convert(name)
end

task :to_b do |name|
convert(name)
end

def convert name
puts "converting #{name}"
end
 
A

Alex Wayne

Joel said:
Not sure I understand, but why not just do what you said: define a
method that handles the common work?

task :to_a do |name|
convert(name)
end

task :to_b do |name|
convert(name)
end

def convert name
puts "converting #{name}"
end

*Slaps forehead*. For some reason, I assumed that is not how a rake
task works. I guess I need to remember its just plain old ruby with
some syntax sugar, right?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,995
Messages
2,570,236
Members
46,822
Latest member
israfaceZa

Latest Threads

Top