Rails Metal

Rails3では無くなった機能なので、今更感たっぷりですが、
Railscasts - Rails Metal
を見て、軽量さに感動したので試してみました。
(今ならsinatraで書くのがいいのかな)

作り方

$ script/generate metal processes_list
# app/metal/processe_list.rb
require(File.dirname(__FILE__) + "/../../config/environment") unless defined?(Rails)  
  
class ProcessesList  
  def self.call(env)  
    if env["PATH_INFO"] =~ /^\/processes_list/  
      [200, {"Content-Type" => "text/html"}, ["Hello, World!"]]  
    else  
      [404, {"Content-Type" => "text/html"}, ["Not Found"]]  
    end  
  end  
end 

が出来上がります。
これだけで、script/server すると動いちゃう。


psの結果を出力するように変更します。

  def self.call(env)
    if env["PATH_INFO"] =~ /^\/processes_list/
      [200, {"Content-Type" => "text/html"}, [`ps -axcr -o "pid, pcpu, pmem, time, comm"`]]
    else
      [404, {"Content-Type" => "text/html"}, ["Not Found"]]
    end
  end

あとは、指定した時間でreloadするようにajaxを使うと。
js読ませるためにerbで受けた結果をmetalに処理させるという書き方です。


まずは、rm public/index.htmlしてroutes.rbを編集。

#config/routes.rb
  map.resources :processes
  map.root :processes
#app/views/processes/index.html.rb
<h1>Processes List</h1>
<pre id="processes">Gathering processes...</pre>
<%= periodically_call_remote :url => "/processes_list", :update => "processes", :frequency => 3, :method => :get %>



#app/views/application.html.erb
<!DOCTYPE HTML>
<html lang="ja">
<head>
  <meta charset="UTF-8">
  <title>metal sample</title>
  <%= javascript_include_tag :defaults %>
</head>
<body>
  <%= yield %>
</body>
</html>

こんな感じ