diff --git a/app.rb b/app.rb new file mode 100644 index 0000000..afc3c27 --- /dev/null +++ b/app.rb @@ -0,0 +1,28 @@ +require_relative 'time_formatter' +class App + def call(env) + @request = Rack::Request.new(env) + time_service_call + end + + def time_service_call + return response(404, 'Path error or time format is nil') if (@request.path != '/time' || user_input.nil?) + + time_service = TimeFormatter.new(user_input) + if time_service.input_valid? + response(200, time_service.time_output) + else + response(404, "Unknown time format(s): #{time_service.unknown_formats}") + end + end + + private + + def response(status, content) + Rack::Response.new([content], status, { 'Content-Type' => 'text/plain' }).finish + end + + def user_input + @request.params['format']&.split(',') + end +end diff --git a/config.ru b/config.ru new file mode 100644 index 0000000..918a83d --- /dev/null +++ b/config.ru @@ -0,0 +1,2 @@ +require_relative 'app' +run App.new diff --git a/time_formatter.rb b/time_formatter.rb new file mode 100644 index 0000000..4f6ffb1 --- /dev/null +++ b/time_formatter.rb @@ -0,0 +1,24 @@ +class TimeFormatter + attr_reader :user_input + + FORMATS = { 'year' => '%Y', 'month' => '%m', 'day' => '%d', 'hour' => '%H', + 'minute' => '%M', 'second' => '%S' }.freeze + + def initialize(user_input) + @user_input = user_input + end + + def input_valid? + unknown_formats.empty? + end + + def unknown_formats + @unknown_formats = user_input - FORMATS.keys + end + + def time_output + output = [] + user_input.each { |el| output.push(FORMATS[el]) if FORMATS[el] } + Time.now.strftime(output.join('-')) + end +end