简体   繁体   English

用于干扰资源访问的Ruby / Rails库

[英]Ruby/Rails library for DRYing up resource access

A common pattern in a Rails controller action is to Rails控制器操作中的常见模式是

  1. Fetch a resource 获取资源
  2. Do something to the resource (optional) 对资源做一些事情(可选)
  3. Return the resource in a serialized format. 以序列化格式返回资源。

I am looking for a library that abstracts away the first step, so that my controller actions can assume a resource was successfully fetched and avoid checks for exceptional cases. 我正在寻找一个抽象出第一步的库,以便我的控制器操作可以假定资源已成功获取并避免检查异常情况。

For example, here is a hypothetical show action: 例如,这是一个假设的show动作:

def show
  attrs   = params.slice(:handle, :provider)
  account = Account.find_by(attrs)

  if account
    respond_with account
  else
    head 404
  end
end

And what I want is something more like this: 我想要的是更像这样的东西:

# controller
def show
  respond_with resource
end

# some initializer (basically pseudocode)
resource do |params|
  attrs = params.slice(:handle, :provider)
  Account.find_by(attrs)
end

Where the library would handle returning a 404 if find_by returns nil, or 400 if the provided params are invalid (missing :handle key, include an extra :id key, etc.). 如果find_by返回nil,库将处理返回404,如果提供的params无效,则返回400(缺少:句柄键,包括额外:id键等)。

Does anyone know of a library that provides something like this? 有谁知道提供这样的东西的图书馆? It is a great use case for a Rack middleware on top of Application.routes . 它是Application.routes之上的Rack中间件的一个很好的用例。

gem platformatec / inherited_resources做了非常接近的事情。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM