📜 ⬆️ ⬇️

How to implement the HMVC pattern in Rails




Rails engins? Not!


This is a great way to create embedded applications. But if you want to make a request to another engine, it will block another instance of your server. Therefore, if you have a high-level HMVC structure, you will need to have many application instances running in order for the application to work.

Solution: async-rails


I believe that a good solution to this problem is sharing Rails engines and async-rails
')
Suppose we have a engine that implements a FooController with a #bar action:
module MyEngine class FooController < ::ApplicationController def bar render the: text => "Your text is #{params[:text]}" end end end 


Add to 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' 


And this line in config.ru:
 ... use Rack::FiberPool # <--   run HmvcTest::Application 


And this is in config / application.rb:
 ... config.threadsafe! # <--   end end 


Now we can make requests from any part of our application in 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 


Now start the server:
 this start 


and open http: // localhost: 3000 / home / index? a = HMVC in the browser:


In the rails log we get:
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)


We made one request inside another. Looks all ok!

Problems


This approach has several drawbacks:


Links


  1. Scaling Web Applications with HMVC article by Sam de FreThe
  2. https://github.com/igrigorik/async-rails

Source: https://habr.com/ru/post/137558/


All Articles