Created
June 1, 2013 10:05
-
-
Save penguin2716/5689892 to your computer and use it in GitHub Desktop.
JSONなAPIを叩くようなやつ
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
#-*- coding: utf-8 -*- | |
# http:// から始まるURLをopenできるようにする | |
require 'open-uri' | |
# JSONをHashに変換するために必要 | |
require 'json' | |
# APIのベースとなるURL | |
BASE_URL = "http://zipcloud.ibsnet.co.jp/api/search?zipcode=" | |
# 引数に郵便番号もしくはその一部を受け取って, | |
# 対応する住所を表示するメソッド | |
# 引数: | |
# zipcode: 郵便番号(またはその一部)の文字列 | |
# show: 結果を出力するかどうか | |
# 戻り値: | |
# APIで受け取ったJSONのHash | |
def get_address(zipcode, show = true) | |
# Java の try{...} catch(Exception e) {...} と同じ | |
# zipcodeから数字のみを抜き出す | |
# 数字がなければ "Invalid zipcode" という例外を発生させる | |
begin | |
zipcode = zipcode.scan(/[0-9]+/).flatten.first | |
raise "Invalid zipcode" if zipcode == nil | |
rescue Exception => e | |
puts e.to_s | |
raise "Invalid zipcode" | |
end | |
# APIをHTTPで叩いて応答をresponseに保存 | |
response = open(BASE_URL + zipcode).read | |
# responseは文字列なのでデータとしては扱いにくい | |
# JSON.parseするとHashになるので使いやすくなる | |
json = JSON.parse(response) | |
# 対応する郵便番号がなければjson["results"]は存在しないので | |
# エラーメッセージを表示して終了する | |
if json["results"] == nil | |
puts "Error: no such zipcode" | |
exit 1 | |
end | |
# 結果を標準出力に表示 | |
puts json["results"].first["address1"] + | |
json["results"].first["address2"] + | |
json["results"].first["address3"] if show | |
# 戻り値はjson (json.class #=> Hash) | |
json | |
end | |
# このファイルが実行されたときはifブロックを実行 | |
# 他のファイルからrequireやloadされた場合は何もしない | |
if $0 == __FILE__ | |
# 引数のチェック | |
# 使用例: | |
# $ ruby json_sample.rb 6100303 | |
if ARGV.size == 0 | |
puts "Usage: #{$0} <zipcode>" | |
exit 1 | |
end | |
# 第一引数でget_addressメソッドを実行 | |
get_address(ARGV[0]) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment