从 Sinatra 内部调用 Sinatra [英] Calling Sinatra from within Sinatra

查看:30
本文介绍了从 Sinatra 内部调用 Sinatra的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个基于 Sinatra 的 REST 服务应用程序,我想从其中一个路由中调用一个资源,有效地从另一个资源组合一个资源.例如

I have a Sinatra based REST service app and I would like to call one of the resources from within one of the routes, effectively composing one resource from another. E.g.

get '/someresource' do
  otherresource = get '/otherresource'
  # do something with otherresource, return a new resource
end

get '/otherresource' do
  # etc.
end

重定向将不起作用,因为我需要对第二个资源进行一些处理并从中创建一个新资源.显然我可以 a) 使用 RestClient 或其他一些客户端框架或 b) 构建我的代码,以便其他资源的所有逻辑都在一个方法中并调用它,但是,如果我可以重新 -在 Sinatra 中使用他们的 DSL 使用我的资源.

A redirect will not work since I need to do some processing on the second resource and create a new one from it. Obviously I could a) use RestClient or some other client framework or b) structure my code so all of the logic for otherresource is in a method and just call that, however, it feels like it would be much cleaner if I could just re-use my resources from within Sinatra using their DSL.

推荐答案

我能够通过发出快速而肮脏的机架请求并直接调用 Sinatra(机架应用程序)应用程序来解决问题.它不漂亮,但它有效.请注意,最好将生成此资源的代码提取到辅助方法中,而不是执行此类操作.但这是可能的,而且可能有比这更好、更清洁的方法.

I was able to hack something up by making a quick and dirty rack request and calling the Sinatra (a rack app) application directly. It's not pretty, but it works. Note that it would probably be better to extract the code that generates this resource into a helper method instead of doing something like this. But it is possible, and there might be better, cleaner ways of doing it than this.

#!/usr/bin/env ruby
require 'rubygems'
require 'stringio'
require 'sinatra'

get '/someresource' do
  resource = self.call(
    'REQUEST_METHOD' => 'GET',
    'PATH_INFO' => '/otherresource',
    'rack.input' => StringIO.new
  )[2].join('')

  resource.upcase
end

get '/otherresource' do
  "test"
end

如果您想了解更多关于幕后发生的事情,我写了几篇关于 Rack 基础知识的文章,您可以阅读.有什么是机架?使用机架.

If you want to know more about what's going on behind the scenes, I've written a few articles on the basics of Rack you can read. There is What is Rack? and Using Rack.

这篇关于从 Sinatra 内部调用 Sinatra的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆