【发布时间】:2018-03-31 14:29:26
【问题描述】:
我创建了一个简约的 Rack 应用程序,它将响应
URL GET /time
带有format查询字符串参数,并以指定格式返回时间。
例如,GET 请求
/time?format=year%2Cmonth%2Cday
将返回一个带有 text/plain 类型和正文 1970-01-01 的响应。
可用的时间格式:年、月、日、时、分、秒
格式以任意顺序传递给“格式”查询字符串参数
如果时间格式中存在未知格式,则应返回状态码为 400 且正文为“未知时间格式 [epoch]”的响应
如果有几种未知格式,则应在响应正文中全部列出,例如:“未知时间格式[epoch,age]”
如果请求任何其他 URL,它应该返回状态码 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
【问题讨论】:
-
你忘了问问题。此外,所有这些机架的东西似乎都无关紧要。没有它可以将用户提供的格式字符串转换为格式化的日期时间。
-
我只需要在正文中转换@user_format[1970-01-01]
标签: ruby-on-rails ruby rack