我想在我的Rails应用程序中挂载一个Sinatra应用程序。但是我希望它们共享相同的布局。
IFrame可能可行,但你有其他想法吗?
谢谢
我想在我的Rails应用程序中挂载一个Sinatra应用程序。但是我希望它们共享相同的布局。
IFrame可能可行,但你有其他想法吗?
谢谢
你基本上需要做两件事情:
你需要告诉Rails路由器,某个特定的URL路径将由另一个Rack应用程序处理(在你的情况下是Sinata应用程序)。这可以通过将以下内容添加到routes.rb来完成:
match "/sinatra" => MySinatraApp, :anchor => false
完成上述步骤后,您可以按照以下方式创建应用程序:
class MySinatraApp < Sinatra::Base
get "/" do
"Hello Sinatra World"
end
end
app/views/layouts/application.html.erb
中,适用于Rails 3.1。默认情况下,Sinatra使用./views/layout.ext
(其中ext
是所选模板系统的扩展名)。因此,你需要告诉Sinatra:
./views
set :views, "/path/to/your/railsapp/views"
set :erb, layout => :"layout/application" # or whatever rendering engine you chose
为了共享相同的布局,您可以将Sinatra指向Rails应用程序中包含布局的文件夹: (摘自这里:http://www.sinatrarb.com/configuration.html)
从您的Rails应用程序中,您可以构建一个方法,您可以从其中调用sinatra应用程序应包含在视图中的操作。 (假设您要使用此操作的索引操作):views - view template directory A string specifying the directory where view templates are located. By default, this is assumed to be a directory named “views” within the application’s root directory (see the :root setting). The best way to specify an alternative directory name within the root of the application is to use a deferred value that references the :root setting:
set :views, Proc.new { File.join(root, "templates") }
def index
@sinatra_content = get_sinatra
end
# use @sinatra_content in your views for rendering
def get_sinatra
sinatra_ip = 127.0.0.1;
sinatra_port = 4567;
#start a request here
RestClient.get 'http://#{sinatra_ip}:{sinatra_port}/', {:params => {:id => 50, 'foo' => 'bar'}}
end
查看 rest-client 的使用方法:https://github.com/archiloque/rest-client,并且不要忘记在你的 Rails 应用程序中包含 gem。
在你的 Sinatra 应用程序中使用链接时,你应该决定是否由 Sinatra 处理(指向 Sinatra 应用程序(带端口)或在你的 Sinatra 应用程序中构建链接,由你的 Rails 应用程序处理)。
我认为在你的Rails应用程序中使用append_view_path
会更好一些。只需将Sinatra视图附加到Rails应用程序中,它就会在查找app/views之后查找那里。
José Valim的《Crafting Rails Applications》一书在这个主题(从其他来源呈现视图)上有很多文档,你可以看一下。
此外,这个Railscasts也可以帮助: http://railscasts.com/episodes/222-rack-in-rails-3