RailsでHMVCパターンを実装する方法







Railsエンジン? いや!



これは、「組み込み」アプリケーションを作成するのに最適な方法です。 ただし、別のエンジンでリクエストを行う場合、サーバーの別のインスタンスがブロックされます。 したがって、高レベルのHMVC構造がある場合、アプリケーションの動作を保証するために、アプリケーションの実行中のインスタンスを多数持つ必要があります。



解決策:async-rails



この問題の良い解決策は、Railsエンジンと非同期レールを一緒に使用することだと思います



#barアクションで特定のFooControllerを実装するエンジンがあるとします:

module MyEngine class FooController < ::ApplicationController def bar render the: text => "Your text is #{params[:text]}" end end end
      
      







Gemfileに追加します。

 gem 'thin' # yes, we're going to use thin! gem 'rack-fiber_pool', :require => 'rack/fiber_pool' # async http requires gem 'em-synchrony', :git => 'git://github.com/igrigorik/em-synchrony.git', :require => 'em-synchrony/em-http' gem 'em-http-request',:git => 'git://github.com/igrigorik/em-http-request.git', :require => 'em-http' gem 'addressable', :require => 'addressable/uri'
      
      







そして、config.ruの次の行:

 ... use Rack::FiberPool # <--   run HmvcTest::Application
      
      







そして、それはconfig / application.rbにあります:

 ... config.threadsafe! # <--   end end
      
      







これで、FooControllerのアプリケーションの任意の部分からリクエストを作成できます。

 class HomeController < ApplicationController def index http = EM::HttpRequest.new("http://localhost:3000/foo/bar?text=#{params[:a]}").get render :text => http.response end end
      
      







サーバーを起動します。

 this start
      
      







http:// localhost:3000 / home / indexを開きますか?a =ブラウザーのHMVC





Railsのログには次のものがあります:

Started GET "/home/index?a=HMVC" for 127.0.0.1 at 2012-02-03 15:27:02 +0400

Processing by HomeController#index as HTML

Parameters: {"a"=>"HMVC"}



Started GET "/foo/bar?text=HMVC" for 127.0.0.1 at 2012-02-03 15:27:02 +0400

Processing by FooController#index as HTML

Parameters: {"text"=>"HMVC"}

Rendered text template (0.0ms)

Completed 200 OK in 1ms (Views: 0.6ms | ActiveRecord: 0.0ms)


Rendered text template (0.0ms)

Completed 200 OK in 6ms (Views: 0.4ms | ActiveRecord: 0.0ms)








別のリクエストを作成しました。 すべてが大丈夫のようです!



問題



このアプローチにはいくつかの欠点があります。





参照資料



  1. Sam de FreTheによるHMVCによるWebアプリケーションのスケーリング記事

  2. https://github.com/igrigorik/async-rails



All Articles