[Script] [postData]This is to upload data to different environment.
#! /usr/bin/env ruby | |
# encoding: UTF-8 | |
require 'httparty' | |
require 'json' | |
require 'active_support/core_ext/hash' | |
Environment = Struct.new(:base_url, :username, :password) do | |
end | |
module Configuration | |
ENTITY_PATH = { | |
:module => "/module/any", | |
:product => "/product/any", | |
} | |
ENV_METADATA = { | |
:SIT => Environment.new("some_url", "sit-username", "sit-password"), | |
:INTEGRATION => Environment.new("integration_url", "integration-username", "integration-password"), | |
:UAT => Environment.new("uat-url", "uat-username", "uat-password"), | |
:LOCAL => Environment.new("http://localhost:8000/", "", "") | |
} | |
def create_url_for_env(env, entity_type) | |
ENV_METADATA[env.to_sym].base_url + '/' +ENTITY_PATH[entity_type.to_sym] | |
end | |
def basic_auth_for_env(env) | |
{:username => ENV_METADATA[env].username, | |
:password => ENV_METADATA[env].password} | |
end | |
end | |
module JsonAttributeReader | |
def read_json_file(file_name) | |
JSON.parse(IO.read(file_name).force_encoding("utf-8").encode("utf-8", replace: nil)) | |
end | |
def json_reader(file_name) | |
read_json_file file_name | |
end | |
end | |
class RequestDispatcher | |
include Configuration | |
include JsonAttributeReader | |
def for_basic_auth_for_env(env) | |
basic_auth_for_env(env) | |
end | |
def post_data(json_file, env) | |
jsons =json_reader json_file | |
type = jsons[0]['type'].split(":")[2].to_sym | |
url = create_url_for_env env, type | |
jsons.each do |json| | |
options = { | |
:body => json, | |
:basic_auth => basic_auth_for_env(env) | |
} | |
res = HttpParty.post url, options | |
puts "result ...#{res}" | |
end | |
end | |
end | |
# Utilities | |
def usage | |
"usage: \n #{$PROGRAM_NAME} <path_to_json_file> ? <path_to_json_folder> \ | |
\n\n Also, you should be running this from the folder, where data is present \n" | |
end | |
def is_folder? argument | |
File.directory? argument | |
end | |
def is_json_file? argument | |
File.file? argument | |
end | |
def current_path | |
Dir.pwd | |
end | |
def create_path arg | |
current_path + "/" +arg | |
end | |
def post_data_to_env path, env | |
request_dispatcher = RequestDispatcher.new() | |
if is_json_file? path | |
puts "In post data " | |
request_dispatcher.post_data path, env | |
request_dispatcher.for_basic_auth_for_env env | |
end | |
if is_folder? path | |
Dir.glob('#{path}/*.json') do |json_file| | |
request_dispatcher.post_data json_file, env | |
end | |
end | |
end | |
if ARGV.length != 2 | |
puts usage | |
else | |
argument = ARGV[0] | |
env = ARGV[1].to_sym | |
path = create_path argument | |
puts "argument : #{argument} .... env : #{env} .........Path : #{path}" | |
post_data_to_env path, env | |
end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment