Making a web page with ruby without rails

前端 未结 4 1502
庸人自扰
庸人自扰 2020-12-14 03:38

I´m looking for a way to do simple ruby code without rails. I´m coming from PHP world, and sometimes, I just build a page with a Mysql connection, run a query and show resul

4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-14 04:21

    The simplest way I know of is to use Ruby's CGI module, and run the script as CGI. Depending on your performance requirements and complexity of the page you want to generate, something like this might just do the trick:

    #!/usr/bin/ruby
    require 'cgi'
    require 'mysql'
    
    con = Mysql.new("localhost","user","pass","mydb")
    rs = con.query('select * from users')
    
    cgi = CGI.new('html4')
    cgi.out {
      cgi.html {
        cgi.body {
          rs.each_hash { |row| puts #{"row['name']} - #{row['age']}" }
        }
      }
    }
    

    You would want to consider the overhead of establishing connection to MySQL on each request, and for complex pages you will need a templating mechanism.

提交回复
热议问题