Posted at

#Ruby で #teratail Tag API(タグを持つ質問)を試してみたメモ

More than 3 years have passed since last update.


環境


  • Windows 7 64bit

  • ruby 2.2.0p0 (2014-12-25 revision 49005) [x64-mswin64_100]

  • Rubyの学習がてら。


teratail API について


Rubyソース


teratail.rb

require 'json'

require 'net/http'
require 'openssl'
require 'uri'

# https://teratail.com/ のアクセストークン管理で取得できるアクセストークンを貼り付ける
TOKEN = ''

class Teratail
@@url = 'https://teratail.com/api/v1/tags/%s/questions'

public

def initialize
self.execute(ARGV)
end

def execute(values)
json = self.fetch(self.keyword(values))
self.echo(json) if json
end

protected

def keyword(values)
if values.length == 0 then
result = 'Ruby'
else
result = values.join(' ')
end
URI.encode_www_form_component(result.encode('UTF-8'))
end

def fetch(value)
uri = URI.parse(@@url % value)
uri.query = URI.encode_www_form({:page => 1, :limit => 5})

req = Net::HTTP::Get.new(uri)
req['Authorization'] = 'Bearer ' << TOKEN

http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE

res = http.start do |h|
h.request(req)
end

JSON.parse(res.body)
end

def echo(json)
questions = json['questions']
questions.each do |row|
row.each do |key, value|
print key, ' = ', value
puts
end
puts
end if questions
end
end

Teratail.new



コマンドプロンプトで実行


cmd

C:\ruby\bin>ruby C:\[teratail.rbのあるパス]\teratail.rb [keyword]




example

C:\ruby\bin>ruby teratail.rb



result

id = 12625

title = rubyの $*[0] という文字の意味がわかりません。$0の意味はわかりますが・・・。
created = 2015-07-11 15:37:49
modified = 2015-07-11 15:37:49
count_reply = 2
count_clip = 0
count_pv = 24
is_beginner = false
is_accepted = false
tags = ["Ruby", "Rails"]
user = {"display_name"=>"*****", "photo"=>"*****", "score"=>50}

id = 12575
title = ja.ymlファイルの正しい書き方
created = 2015-07-10 15:41:19
modified = 2015-07-10 15:41:19
count_reply = 1
count_clip = 0
count_pv = 23
is_beginner = true
is_accepted = false
tags = ["Ruby", "Rails"]
user = {"display_name"=>"*****", "photo"=>"*****", "score"=>43}

:
:
:


https://teratail.com/tags/Ruby

「新着」の内容を取得可能な模様



example

C:\ruby\bin>ruby teratail.rb AWS(Amazon Web Services)



result

id = 12539

title = confd で backend に dynamodb を使用するには?
created = 2015-07-09 22:48:40
modified = 2015-07-09 23:02:55
count_reply = 0
count_clip = 0
count_pv = 12
is_beginner = false
is_accepted = false
tags = ["AWS(Amazon Web Services)", "Go"]
user = {"display_name"=>"*****", "photo"=>"*****", "score"=>2}

id = 12190
title = WARファイルをAWSのEC2にコマンドプロンプトを用いてデプロイしたい
created = 2015-07-03 23:50:06
modified = 2015-07-03 23:50:06
count_reply = 0
count_clip = 0
count_pv = 14
is_beginner = true
is_accepted = false
tags = ["MacOS(OSX)", "AWS(Amazon Web Services)"]
user = {"display_name"=>"*****", "photo"=>"*****", "score"=>38}

:
:
:


https://teratail.com/tags/AWS%28Amazon+Web+Services%29

「新着」の内容を取得可能な模様