Danil Panshin
Danil Panshin

Reputation: 123

simple Rack app which will respond to URL GET /time?format=year%2Cmonth%2Cday with 1970-01-01

I have created a minimalistic Rack application that will respond to

URL GET /time

with the format query string parameter and return the time in the specified format.

For example, a GET request

/time?format=year%2Cmonth%2Cday

will return a response with a text/plain type and a body 1970-01-01.

there is my code:

config.ru

require_relative 'middleware/logger'
require_relative 'app'

use AppLogger
run App.new

logger.rb

require 'logger'

class AppLogger

  def initialize(app, **options)
    @logger = Logger.new(STDOUT)
    @app = app
  end

  def call(env)   
    @logger.info(env)
    @app.call(env)
  end

end

app.rb

class App

  def call(env)  
    @query = env["QUERY_STRING"] 
    @path = env["REQUEST_PATH"]
    @user_format = (Rack::Utils.parse_nested_query(@query)).values.join.split(",")
    @acceptable_format = %w(year month day hour minute second)
    [status, headers, body]
  end

  private 

  def status
    if @path == "/time" && acceptably?
      200
    elsif @path == "/time"
      400
    else
      404
    end      

  end

  def headers
    { 'Content-Type' => 'text/plain' }
  end

  def body
    if @path == "/time" && acceptably?
      **#to do** 
    elsif @path == "/time"
      ["Unknown time format #{unknown_time_format}"]
    else
      ['Not found']    
    end
  end

  def acceptably?
    (@user_format - @acceptable_format).empty?
  end 

  def unknown_time_format
    @user_format - @acceptable_format
  end

end

Upvotes: 0

Views: 370

Answers (1)

Danil Panshin
Danil Panshin

Reputation: 123

def convert_user_format
  @user_format.map! { |t| case t
                            when "year"
                              t = Time.now.year
                            when "month"
                              t = Time.now.month
                            when "day"
                              t = Time.now.day
                            when "hour"
                              t = Time.now.hour
                            when "minute"
                              t = Time.now.min
                            when "second"
                              t = Time.now.sec        
                          end     
                        }
  @user_format.join("-")                           
end

def body
  if @path == "/time" && acceptably?
    [convert_user_format]
... 

Upvotes: 0

Related Questions