Search code examples
rubyrake

Access variable from another rake namespace


I have a lot of rake tasks in nested namespaces.

All my tasks has pretty much the same structure, so instead of writing documentation for each, I want to generate documentation, using the configuration variables that exist in each namespace.

Small example:

namespace :metadata do |ns|
    config = {:data_location=>"/mnt/metadata/",
              :data_description=>"Metadata from system 5"}
    task :process do |task|
        # Code
    end
end

namespace :frontend_log do |ns|
    config = {:data_location=>"/mnt/backend/",
              :data_description=>"Logdata from backend"}
    task :process do |task|
        # Code
    end
end


namespace :backend_log do |ns|
    config = {:data_location=>"/mnt/backendlog/",
              :data_description=>"Logdata from backend"}
    task :process do |task|
        # Code
    end
end

Imagine 150 more of these namespaces.

namespace :documentation do |ns|
    task :generate do |task|
        # For each namespace that has a configuration
        # Generate a sentence about that namespace
    end
end

Output example:

:metadata:process will process data from the /mnt/metadata folder, which contains Metadata from system 5

:frontend_log:process will process data from the /mnt/backend folder, which contains Logdata from backend

and so on.

How do I get the config of :metadata inside :documentation:generate?

I am doing this to avoid refactoring code, suggestions to refactor are welcome if they are constructive, but really, it's not the reason I ask this question.


Solution

  • So by now I have solved it in this way:

    namespace :metadata do |ns|
        config = {:data_location=>"/mnt/metadata/",
                  :data_description=>"Metadata from system 5"}
        task :process do |task|
            # Code
        end
        task :document do |task|
            selfdocument(config)
        end
    end
    
    namespace :frontend_log do |ns|
        config = {:data_location=>"/mnt/backend/",
                  :data_description=>"Logdata from backend"}
        task :process do |task|
            # Code
        end
        task :document do |task|
            selfdocument(config)
        end
    end
    
    namespace :backend_log do |ns|
        config = {:data_location=>"/mnt/backendlog/",
                  :data_description=>"Logdata from backend"}
        task :process do |task|
            # Code
        end
        task :document do |task|
            selfdocument(task, config)
        end
    end
    

    With a helper function

    def selfdocument(task, config) do
        puts "#{task} will process data from the #{config[:data_location]} folder, which contains #{config[:data_description]}"
    end
    

    Which is not a rewrite or refactor per say, since I am only adding a task, not moving code around or changing existing code.