Rails: Single File App

Posted by luca
on Tuesday, June 03

I took inspiration from the Pratik Naik post, and realized a more simplistic version of its Rails single file app. My implementation has only Rails as unique dependency.

require 'rubygems'
require 'action_controller'
require 'webrick'
require 'webrick_server'

class HelloWorldController < ActionController::Base
  session :off
  def index; render :text => 'Hello World!' end
end

ActionController::Routing::Routes.draw do |map|
  map.root :controller => "hello_world"
end

DispatchServlet.dispatch :port => 3000,
    :server_root  => File.dirname(__FILE__)

Update 2008-06-04: I just wrote another version which also uses ActiveRecord and a template.

require 'rubygems'
require 'activerecord'
require 'action_controller'
require 'webrick'
require 'webrick_server'

ActiveRecord::Base.establish_connection(
  :adapter  => 'sqlite3',
  :database => 'tiny_rails.sqlite3',
  :timeout  => 5000)

ActiveRecord::Schema.define do
  create_table :people, :force => true do |t|
    t.string :first_name
  end
end
class Person < ActiveRecord::Base; end
Person.create :first_name => 'Luca'

File.open('index.html.erb', 'w') do |f|
  f << "Hello, my name is <%=h @person.first_name %>!\n"
end

class HelloWorldController < ActionController::Base
  session :off
  def index
    @person = Person.find :first
    render :file => 'index.html.erb'
  end
end

ActionController::Routing::Routes.draw do |map|
  map.root :controller => "hello_world"
end

DispatchServlet.dispatch :port => 3000,
    :server_root  => File.dirname(__FILE__)

Just start the script and point your browser at http://localhost:3000!