hello-world
webエンジニアのメモ。とりあえずやってみる。

[sinatra][twitter]screen_nameからユーザidを求めるサンプル

公開日時

twitterのscreen_nameを元にユーザidを知りたいと思い調べていたところ、

https://twitter.com/intent/user?screen\_name={screen\_name}

でアクセスしたhtmlソースのmetaタグに

<meta name="native-url" content="twitter://user?id={ユーザID}">

が書かれているということが分かりました。

毎回urlにアクセスしてソースを見るのは手間だったのと、sintraでちょっとしたサンプルを作ってみたいと思っていたので、 screen_nameからユーザidを求めるサンプルを作ってみました。

フォームに入力されたscreen_nameからnokogiriを使ってユーザIDを取得してきています。

サクッとサンプルを試したいときにはsinatra便利ですね。

# app.rb
require 'sinatra'
require 'erb'
require 'open-uri'
require 'nokogiri'
require 'pry'

get '/' do
  @screen_name = "xxxx"
  erb :index
end

post '/' do
  uid = @params[:uid]
  redirect back if uid.nil? || uid.empty?
  begin
    doc = Nokogiri::HTML(open("https://twitter.com/intent/user?screen_name=#{uid}"))
    native_url = doc.css('meta[name="native-url"]').first.attribute('content').value
    res = native_url.match(%r{^twitter://user\?id=(\d+)$})
    @screen_name = res[1]
  rescue OpenURI::HTTPError => e
    if e.message == '404 Not Found'
      @screen_name = "404 Not Found"
    else
      raise e
    end
  end
  erb :index
end

__END__
@@index
<html>
<body>
  <p>twitter screen_name converter</p>
  <form action="/" method="post">
    <input type="text" maxlength="30" name="uid" placeholder="input screen_name">
    <input type="submit">
  </form>
  uid is <%= @screen_name %>
</body>
</html>

# Gemfile
source 'https://rubygems.org'

gem 'sinatra'
gem 'nokogiri'
gem 'pry'

参考


Related #Ruby

[Rails]find_or_create_byとfind_or_initialize_by

Rails4で確認。

capistranoで世代管理する際の注意点

最近、デプロイツールに capistranoを使っているのですが、世代管理の設定を勘違いしていたのでメモを残しておきます。

[rails]unicornでpryを使う

先日、pryでデバッグする という記事を書きましたが、こちらはrails server(フォアグランド)でアプリを立ち上げた際のデバッグ方法でした。