我创建了一个简约的Rack应用程序,它将响应
URL GET /time
使用format
查询字符串参数并以指定格式返回时间。
例如,GET请求
/time?format=year%2Cmonth%2Cday
将返回带有text / plain类型和body 1970-01-01的响应。
可用时间格式:年,月,日,小时,分钟,秒
格式传递给'格式'按任意顺序查询字符串参数
如果时间格式中存在未知格式,则应返回状态码为400且正文为"未知时间格式[epoch]"
如果有多种未知格式,则应在响应正文中列出所有格式,例如:"未知时间格式[纪元,年龄]"
如果请求任何其他网址,则应返回状态代码为404
有我的代码:
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
答案 0 :(得分:0)
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]
...