I am trying to create a rake file with tasks for consuming my API. I want to be able and pass a lot of arguments to the task, depending on the call to be used. In an effort to make the tasks easier to use, I want the namespace to be part of the configuration. Is this possible?
namespace :myAPI do
SERVER = 'local'
namespace :live do
SERVER = 'live'
end
namespace :beta do
SERVER = 'beta'
end
BASE_URI = {
live: "https://myapi.com/do/v1",
beta: "https://beta.myapi.com/do/v1",
local: "http://127.0.0.1:4500/do/v1"
}
desc 'Get currently logged users'
task :extract_logged_users => :environment do
get("BASE_URI[SERVER]/users/current")
end
}
And then I want to be able and run this against the live server for example:
rake myAPI:live:extract_logged_users
You can create the task in a mor dynamic way like this:
require 'rake'
BASE_URI = {
live: "https://myapi.com/do/v1",
beta: "https://beta.myapi.com/do/v1",
local: "http://127.0.0.1:4500/do/v1"
}.each do |server,url|
namespace :myAPI do
namespace server do |ns|
desc 'Get currently logged users'
task :extract_logged_users do
puts 'get("%s/users/current", %s)' % [server,url]
end
end
end
end
(I replaced your get command with puts
to check what happens and added the url into the command).
Now you can call:
rake myAPI:live:extract_logged_users
rake myAPI:beta:extract_logged_users
rake myAPI:local:extract_logged_users
The output:
get("live/users/current", https://myapi.com/do/v1)
get("beta/users/current", https://beta.myapi.com/do/v1)
get("local/users/current", http://127.0.0.1:4500/do/v1)
Alternative coding:
namespace :myAPI do
BASE_URI = {
live: "https://myapi.com/do/v1",
beta: "https://beta.myapi.com/do/v1",
local: "http://127.0.0.1:4500/do/v1"
}
BASE_URI .keys.each do |key|
namespace key do |ns|
desc 'Get currently logged users'
task :extract_logged_users do
puts 'get("%s")' % BASE_URI[key]
end
end
end
end