我们首先不用任何框架,直接用 Rack
、erubi
、sqlite3
构建一个 Web app。
本着不作不死的精神,今晚我又准备现场撸代码了。
代码先贴在这里:
# config.ru require "erubi" $LOAD_PATH << '.' module Simp class Application def self.call(env) [200, {"Content-Type" => "html"}, [html(env["REQUEST_PATH"][1..-1])] ] end def self.render(file_name) eval Erubi::Engine.new( File.read("#{file_name}.html.erb") ).src end def self.render_400 "Oops, the page you visited is not exist." end def self.html(file_name) root_path = '/Users/i/Code/iClean/P7RubyTraining/webapp' file_name = File.join(root_path, file_name) p file_name if File.exist?("#{file_name}.html.erb") render file_name else render_400 end end end end run Simp::Application
index 页面代码
# index.html.erb <% $LOAD_PATH << '.' require 'model' @students = Student.all p @students %> <html> <head> <title>Simp is not a web framework.</title> <head> <body> <table> <tr> <td>Name</td> <td>Email</td> <td>Grade</td> <td>Blog</td> </tr> <% @students.each do |student| %> <tr> <td><%= student['name'] %></td> <td><%= student['email'] %></td> <td><%= student['grade'] %></td> <td><%= student['blog'] %></td> </tr> <% end %> </table> </body> </html>
# model.rb require 'sqlite3' class Student # Open a database DB = SQLite3::Database.new "test.db" def self.all @students = [] DB.execute( "select * from students" ) do |row| student = {} student['name'], student['email'], student['grade'], student['blog'] = row @students << student end @students end end
在运行前记得先生成数据库:
require "sqlite3" # Open a database db = SQLite3::Database.new "test.db" # Create a table rows = db.execute <<-SQL create table numbers ( name varchar(30), val int ); SQL # Execute a few inserts { "one" => 1, "two" => 2, }.each do |pair| db.execute "insert into numbers values ( ?, ? )", pair end # Find a few rows db.execute( "select * from numbers" ) do |row| p row end # Create another table with multiple columns db.execute <<-SQL create table students ( name varchar(50), email varchar(50), grade varchar(5), blog varchar(50) ); SQL # Execute inserts with parameter markers db.execute("INSERT INTO students (name, email, grade, blog) VALUES (?, ?, ?, ?)", ["Jane", "me@janedoe.com", "A", "http://blog.janedoe.com"]) db.execute( "select * from students" ) do |row| p row end
在根目录下面运行:
rackup -p 3000
一个不需要框架的 Web app 就搭建完成啦。
这样直接写过 Web app 的估计年龄都差不多 38+了吧,我大概猜。