答复: Sinatra:一个可以作为Rails有益补充的框架. 简洁而不简单

既然是这么简单的事情,用rack写也比较有趣:
一共5个文件,views里面和搂主的一样:
|-- app.rb
|-- config.yml
|-- console
`-- views
    |-- index.html
    `-- success.html



app.rb
#!/usr/bin/env ruby
require "rubygems"
require "rack"
require "yaml"
require "logger"
require 'active_record'

config = YAML::load(File.open(File.dirname(__FILE__) + "/config.yml"))
ActiveRecord::Base.establish_connection(config)

class Email < ActiveRecord::Base
  validates_presence_of :email  
  validates_format_of :email,:with => /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/i
end


def process_request(env)
  request = Rack::Request.new(env)
  if request.post?
    Email.create! :email => request.params["email"] rescue  return "Email Format Error!"
    File.read("views/success.html")
  else
    "invalide request!"
  end
end


builder = Rack::Builder.new do

  use Rack::CommonLogger, Logger.new("/var/log/rack.log")

  use Rack::ContentType, "text/html"

  use Rack::ContentLength
  
  
  map "/" do
    run lambda{|env| [200, {}, File.read("views/index.html")]}
  end

  map "/contact" do
    run lambda{|env| [200, {}, process_request(env)]}
  end
end

Rack::Handler::Mongrel.run builder, :Port => 8080



config.yml

adapter: mysql
encode: utf8
host: localhost
username: root
password: ******
database: contacts


运行:
sudo chmod +x ./*
./app.rb


模仿rails写了一个简单的console:
console
#!/usr/bin/env ruby
require 'rubygems'
require 'yaml'
require 'active_record'
require 'irb'
require 'irb/completion'

config = YAML::load(File.open(File.dirname(__FILE__) + "/config.yml"))
ActiveRecord::Base.establish_connection(config)

class Email < ActiveRecord::Base
end

IRB.start          


运行console:
hooopo@x-hooopo:~/contact$ ./console
Irbrc Loading...
>> enable_hirb
=> true
>> Email.all
+----+-------------------+--------------------------------+
| id | email             | created_at                     |
+----+-------------------+--------------------------------+
| 1  | [email protected] | Sun Apr 04 22:44:46 +0800 2010 |
| 2  | [email protected]  | Sun Apr 04 22:58:56 +0800 2010 |
+----+-------------------+--------------------------------+
2 rows in set
>> 


你可能感兴趣的:(框架,Ruby,Rails,rack,Sinatra)