へっぽこエンジニアの日誌

へっぽこエンジニアからのレベルアップをはかる

Mac OS Xでdockerを使う

dockerをmacで使いやすくなったので、試してみる。 brewで入れられるようなので、それで。

流れとしては、

  1. brewのアップデート
  2. brewによるインストール
  3. 環境変数の設定

という感じで。

1
2
3
4
5
$ brew update
$ brew install boot2docker
$ export DOCKER_HOST=tcp://
$ boot2docker init
$ boot2docker up

これで準備完了。あとは、dockerfileを落としてきたり何やらしたりできる。

jQueryのoffsetで正確な値を取得する

jQueryのoffsetを使って、topの値を取得しようとした時、想定と違った値がかえってくることがある。 それは、onReadyで実行した場合。 onReadyでは、画像の読み込みが終わる前に実行されるので、画像の高さ分がずれることがある。

対策としては、javascriptのonloadを使うことだが、onloadとonreadyで競合するので、イベントを追加することで対応する。 具体的なコードとしては、こんな感じ。

1
2
3
jQuery.event.add(window, "load", function(){ 
  var hoge = $("#hoge").offset.top;
});

Rubyからgoogle Analyticsのデータを取得する

google apis consoleにアクセスし、プロジェクトを作成。 その後、serviceメニューからanalytics apiをonにする。 API Accessメニューから、アプリを作成し、Certificateでアカウントを作成する。 作成時にできたprivatekey.p12をダウンロードしておく。

アカウント作成時のアドレスyourapp@developer.gserviceaccount.comをanalyticsのユーザーとして登録。

これで準備は完了。

ライブラリをインストールする。

1
gem install google-api-client

サンプルを使う。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# Inspired by https://gist.github.com/3166610
require 'google/api_client'
require 'date'

# Update these to match your own apps credentials
service_account_email = 'yourapp@developer.gserviceaccount.com' # Email of service account
key_file = 'privatekey.p12' # File containing your private key
key_secret = 'notasecret' # Password to unlock private key
profileID = '123456' # Analytics profile ID.


client = Google::APIClient.new()

# Load our credentials for the service account
key = Google::APIClient::KeyUtils.load_from_pkcs12(key_file, key_secret)
client.authorization = Signet::OAuth2::Client.new(
  :token_credential_uri => 'https://accounts.google.com/o/oauth2/token',
  :audience => 'https://accounts.google.com/o/oauth2/token',
  :scope => 'https://www.googleapis.com/auth/analytics.readonly',
  :issuer => service_account_email,
  :signing_key => key)

# Request a token for our service account
client.authorization.fetch_access_token!

analytics = client.discovered_api('analytics','v3')

startDate = DateTime.now.prev_month.strftime("%Y-%m-%d")
endDate = DateTime.now.strftime("%Y-%m-%d")

visitCount = client.execute(:api_method => analytics.data.ga.get, :parameters => { 
  'ids' => "ga:" + profileID, 
  'start-date' => startDate,
  'end-date' => endDate,
  'metrics' => "ga:visits",
})

プロファイルIDは日本語のanalytics画面だと、「ビュー ID 」となっているので、注意が必要。

Debuggerのinstallに失敗した時の対処法

boxenとrbenv使用時にdebuggerのインストールでコケた。 以下がエラー内容。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
checking for rb_method_entry_t.called_id in method.h... no
checking for rb_control_frame_t.method_id in method.h... no
checking for rb_method_entry_t.called_id in method.h... no
checking for rb_control_frame_t.method_id in method.h... no
Makefile creation failed
**************************************************************************
No source for ruby-2.0.0-p353 provided with debugger-ruby_core_source gem.
**************************************************************************
*** extconf.rb failed ***
Could not create Makefile due to some reason, probably lack of necessary
libraries and/or headers.  Check the mkmf.log file for more details.  You may
need configuration options.

Provided configuration options:
     --with-opt-dir
     --without-opt-dir
     --with-opt-include
     --without-opt-include=${opt-dir}/include
     --with-opt-lib
     --without-opt-lib=${opt-dir}/lib
     --with-make-prog
     --without-make-prog
     --srcdir=.
     --curdir
     --ruby=/opt/boxen/rbenv/versions/2.0.0-p353/bin/ruby
     --with-ruby-dir
     --without-ruby-dir
     --with-ruby-include
     --without-ruby-include=${ruby-dir}/include
     --with-ruby-lib
     --without-ruby-lib=${ruby-dir}/

以下が対処法。

1
2
gem install debugger-ruby_core_source --no-rdoc --no-ri -- --with-ruby-include=/opt/boxen/rbenv/versions/2.0.0-p353
gem install debugger-linecache -- --with-ruby-include=/opt/boxen/rbenv/versions/2.0.0-p353

で、改めてdebuggerをインストールしなおす。

Railsで接続するcharetを指定する

railsでは、dbに接続するcharsetを指定しないと、エンコーディングがlatin1になってしまうので、 予め指定をしておいく。

config/database.ymlを開く。

1
2
3
  encoding: utf8
  charset: utf8
  collation: utf8_general_ci

それぞれに上記を記述する。collationも、あらかじめ指定しておいたほうが、あとから変わらなくていいかもしれないので、とりあえず。

Parallelで簡単並列処理

railsで3万行程度のレコードをダミーデータに書き換えるために、並行処理を行うようにparallelを使ってみた。

Gemfileに以下を記述

1
2
gem "parallel"
gem "gimei"

そしてインストール。

1
bundle install

今回はUserモデルの名前を偽名に書き換える処理を行ったので、gimeiライブラリもあわせて入れる。

1
2
3
4
users = User.all
Parallel.each(users, in_threads: 3) do |user|
  user.update_attributes( name: Gimei.new.kanji )
end

スレッドの数を多くすると、コネクションのMAX値を超えてしまうこともあるので、要注意