From 618a5cc0c243896058cf3de3c21d6bfc7d1f44f1 Mon Sep 17 00:00:00 2001 From: Abhay Rana Date: Mon, 21 Nov 2016 22:11:25 +0530 Subject: [PATCH] Refactors the config logic to separate class --- app.rb | 27 ++++----------------------- lightsaber.rb | 51 +++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 55 insertions(+), 23 deletions(-) create mode 100644 lightsaber.rb diff --git a/app.rb b/app.rb index 84bf23e..6b24f6e 100644 --- a/app.rb +++ b/app.rb @@ -1,30 +1,11 @@ require 'rubygems' +require 'pp' require 'bundler/setup' require 'sinatra' require 'yaml' - -def get_url(domain_object, rel_route) - if domain_object.is_a? Hash - return domain_object['root'] + "/" + rel_route - elsif domain_object.is_a? String - return domain_object - end -end +require_relative './lightsaber' get '/*' do - hostname = request.host - route = params[:splat][0] - - YAML::load_file('redirects.yml').each do |code, zone| - if zone.has_key? hostname - url = get_url(zone[hostname], route) - if url - redirect url, code - else - halt 400, "Invalid configuration for #{hostname}" - end - end - end - - halt 404, "#{hostname} hasn't been setup yet." + saber = Lightsaber.new(request.url) + saber.get_response.finish end \ No newline at end of file diff --git a/lightsaber.rb b/lightsaber.rb new file mode 100644 index 0000000..c25f8de --- /dev/null +++ b/lightsaber.rb @@ -0,0 +1,51 @@ +require 'uri' +require 'rack/response' + +# This is the class that resolves a given URL +# to what we need to redirect to +class Lightsaber + + def initialize(url) + @url = URI(url) + end + + def get_url(domain_object, rel_route) + if domain_object.is_a? Hash + return domain_object['root'] + "/" + rel_route + elsif domain_object.is_a? String + return domain_object + end + end + + def get_response_from_yml + res = Rack::Response.new + + YAML::load_file('redirects.yml').each do |code, zone| + if zone.has_key? @url.host.to_s + url = get_url(zone[@url.host], @url.path) + if url + res.redirect url, code + else + res.status = 400 + res.body = "Invalid configuration for #{@url.host}" + end + return res + end + end + end + + def not_setup_response + res = Rack::Response.new + res.status = 404 + res.body = "#{@url.host} hasn't been setup yet." + end + + + def get_response + + yml_res = get_response_from_yml + return yml_res unless yml_res.nil? + + not_setup_response + end +end \ No newline at end of file