[Ruby]formの値を受け取る

formの値を受け取る

サンプル

#!/usr/bin/ruby-1.9.3
# coding: utf-8
require 'cgi'

puts "Content-type: text/plain\n\n"
cgi = CGI.new
keys=cgi.keys
keys.each{|value|
    puts value+" = "+cgi[value]+"\n"
}

[Ruby]ファイルを読み込む

ファイルを読み込む

サンプル

#!/usr/bin/ruby-1.9.3
# coding: utf-8
require 'json'

puts "Content-type: application/json\n\n"

filename="test.txt"
results=Array.new

if File.exist?(filename)
    f = open(filename)
    f.each{|line|
        results.push(line.force_encoding("utf-8"))
    }
    f.close
else
    results.push("no data")
end

puts JSON.generate({'time'=>Time.now.strftime("%Y-%m-%d %H:%M:%S"), 'data'=>results})

[Ruby]MySQLからデータ取得

MySQLからデータ取得

サンプル

#!/usr/bin/ruby-1.9.3
# coding: utf-8
require 'json'
require 'mysql'

puts "Content-type: application/json\n\n"

connection = Mysql.connect('host','user','password','db name')
connection.query("set character set utf8") #文字化けするとき

columns=["ID","post_title","post_date"]
result = connection.query("SELECT "+columns.join(",")+" FROM wp_posts WHERE post_status='publish' ORDER BY ID DESC LIMIT 5")
connection.close

results=Array.new
result.each {|record|
    w = {}
    record.each_with_index{|val,i|
        key = columns[i]
        w[key.force_encoding("utf-8")]=val.force_encoding("utf-8") #文字化けするときforce_encoding
    }
    results.push(w)
}
puts JSON.generate({'time'=>Time.now.strftime("%Y-%m-%d %H:%M:%S"), 'data'=>results})

[Ruby]jsonを出力する

jsonを出力する

サンプル

#coding:utf-8
require 'json'
print("Content-type: application/json\n\n")

print JSON.generate({"time"=>Time.now.strftime("%Y-%m-%d %H:%M:%S"),
                    "user"=>[
                                {"id" => 32, "name"=>"jeff"},
                                {"id" => 56, "name"=>"john"}
                            ]
                    })