First, Ruby is not like php. No droping files into public_html and expecting everything to work.
Never the less, it is possible to do it that way, kinda. So we are using Mysql adapter with no ORM as php does by default.
Before you start, you will need mysql adapter, so install it with:
gem install mysql2
Than write something like:
require "rubygems"
require "mysql2"
client = Mysql2::Client.new(
:host => "127.0.0.1",
:username => "root",
:password => "",
:database => "mydb"
)
records = client.query("SELECT * FROM users")
records.each {|r| p "<p>#{r['name']} - #{r['age']}</p>"}
Now run it in console with
ruby name_of_the _file.rb
This will output records in console. If you want browser output, you will have to write a small server:
#!/usr/bin/ruby
require 'rubygems'
require 'socket'
require 'mysql2'
webserver = TCPServer.new('127.0.0.1', 6789)
client = Mysql2::Client.new(
:host => "127.0.0.1",
:username => "root",
:password => "",
:database => "mydb"
)
records = client.query("SELECT * FROM users")
while (session = webserver.accept)
session.print "HTTP/1.1 200/OK
Content-type:text/html
"
request = session.gets
records.each {|r| session.print "<p>#{r['name']} - #{r['age']}</p>"}
session.close
end
Now when you do ruby application.rb
, server will be started on port 6789 and it will output required data. You can later reverse proxy on it and use it on port 80.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…