August 25, 2013

RailsでHaml(とRSpec)を使えるようにするメモ

GitLabのソースでも見ながら勉強しようかなーと思っていて、GitLabがHaml(とRSpec)を使っているので、メモです。

1. Gemfile に以下を追記
gem 'haml-rails'
2. bundle install を実行してコントローラを作成
$ bundle install
$ rails g controller index index
      create  app/controllers/index_controller.rb
       route  get "index/index"
      invoke  haml
      create    app/views/index
      create    app/views/index/index.html.haml
      invoke  test_unit
      create    test/controllers/index_controller_test.rb
      invoke  helper
      create    app/helpers/index_helper.rb
      invoke    test_unit
      create      test/helpers/index_helper_test.rb
      invoke  assets
      invoke    coffee
      create      app/assets/javascripts/index.js.coffee
      invoke    scss
      create      app/assets/stylesheets/index.css.scss
3. 生成された views/index/index.html.haml ファイルを確認
%h1 Index#index
%p Find me in app/views/index/index.html.haml
4. index#indexにアクセス
5. RSpec
Gemfile に以下を追記して、同じ要領でした。
gem 'rspec-rails'

August 23, 2013

FluentdでMySQLのスロークエリログをMongoDBに保存してみる

1. スロークエリの設定を済ませます。

MySQLのスロークエリログの設定メモ
http://madroom-project.blogspot.jp/2013/08/mysql.html

2. fluent-plugin-mysqlslowquery をインストールします。
$ sudo fluent-gem install fluent-plugin-mysqlslowquery
3. /etc/fluent/fluent.conf を編集します。
<source>
  type mysql_slow_query
  path /var/log/mysql/mysql-slow.log
  tag mongo.mysql.slow
</source>
<match mongo.mysql.slow>
  type mongo
  database fluent
  collection mysql.slow
</match>
3. fluentdを起動します。
$ sudo fluentd
4. 適当にクエリを発行します。
$ mysql -u root -p[パスワード] mysql
mysql> select * from db where 1 = 1;
5. MongoDB側を確認します。(反映まで少しラグがあるかも)

MySQLのスロークエリログの設定メモ

なんでもない内容ですが。。。メモです。

1. my.cnfに以下を記述
[mysqld]
slow_query_log = ON
slow_query_log_file = /var/log/mysql/mysql-slow.log
long_query_time = [秒数(小数可)]
2. MySQLを再起動
"long_query_time"よりも時間がかかるクエリの内容が"slow_query_log_file"に出力されます。とりあえず確認する目的なら"long_query_time"を0にすると、たぶん全部出力されます。

次はこれをFluentdでMongoDBに保存してみようと思います。

FluentdでApacheのアクセスログをMongoDBに保存するメモ(Ubuntu13.04)

メモです。

FluentdとMongoDBのインストールは済ませてある前提です。

1. fluent-plugin-mongoをインストール
sudo fluent-gem install fluent-plugin-mongo

2. /var/log/fluent ディレクトリを作成

3. /etc/fluent/fluent.conf を作成
<source>
  type tail
  format apache2
  path /var/log/apache2/access.log
  pos_file /var/log/fluent/apache2.access_log.pos
  tag mongo.apache.access
</source>
<match mongo.apache.access>
  type mongo
  database fluent
  collection apache.access
</match>
4. 確認
$ sudo fluentd
ブラウザから適当にアクセスして DB => fluent, コレクション => apache.access を確認。

5. 備考
まだあまり調べていないんですが、見た感じ、sourceでpath値のログファイルをtailしつつ、pos_file値の名前で保存。tag値でタグを付けておく。matchでタグ名(ワイルドカードも可)を指定して、設定の通りに処理をする。みたいな感じですかね。

次はMySQLのスロークエリをやってみよう。

--

追記:
"pos_file"について参考 http://colopl.co.jp/tech/blog/2012/05/1808/

August 18, 2013

Vagrantのローカル開発環境でホスト側からMySQLに接続する

SSHで接続しても良いんですが、XAMPPとかMAMPのような感じでローカルの3306(ではなく3366)に直接接続できる感じにしてみました。以下、飽くまでローカル開発環境の話なので、セキュリティ周りは考慮していません。尚、使用しているOSはUbuntu13.04です。

ポイントは以下の3つでした。

1. Vagrantfileで":forwarded_port"の設定をします。ホストの3366がゲストの3306を指すようになります。
config.vm.network :forwarded_port, guest: 3306, host: 3366
2. "/etc/mysql/my.cnf"の"bind-address"の設定をします。ゲストのMySQLにリモートからのアクセスを許可させます。
bind-address  = 0.0.0.0
3. SQLを実行します。rootユーザがリモートからアクセスできるようになります。
GRANT ALL PRIVILEGES ON *.* TO root@'%' IDENTIFIED BY 'xxxxxxxxxx' WITH GRANT OPTION
2と3を反映したChefのレシピは、以下のようになりました。
* node['mysql']['password'] はVagrantfileの"chef.json"に書きます。レシピに直書きでもOKです。
# MySQLのインストール
package 'mysql-server' do
    action :install
    notifies :run, 'execute[mysqladmin]'
    notifies :run, 'execute[mysql]'
end

# パスワードの変更(初回のみ実行される)
execute 'mysqladmin' do
    action :nothing
    command 'mysqladmin password -u root ' + node['mysql']['password']
end

# リモート(ホスト)からの接続を許可(初回のみ実行される)
execute 'mysql' do
    action :nothing
    command "mysql -u root -p#{node['mysql']['password']} -e \"GRANT ALL PRIVILEGES ON *.* TO root@'%' IDENTIFIED BY '#{node['mysql']['password']}' WITH GRANT OPTION\""
end

# サービスを有効にしてスタート
service 'mysql' do
    supports :status => true, :restart => true, :reload => true
    action [:enable, :start]
end

# 前述の"bind-address"の設定を反映する
template '/etc/mysql/my.cnf' do
    notifies :restart, 'service[mysql]'
end
適当なGUIクライアントソフトからlocalhost:3366にrootユーザで接続できればOKです。(ほんとは専用のユーザを用意した方が良いんだろうけど。)

August 17, 2013

Gmailを新しいデザインにしたらInboxのラベル識別子が変わっていたのでAndroidアプリを修正した

以前はGmailのInboxのラベル識別子(?)は "^i" でしたが、WEBで新しいデザインにしたら "^sq_ig_i_personal" に変わってました。他に2つあるようですが今回は関係ないので割愛します。

Android用に提供されている com.google.android.gm.contentprovider の GmailContract クラスだと
GmailContract.Labels.LabelCanonicalNames.CANONICAL_NAME_INBOX
から
GmailContract.Labels.LabelCanonicalNames.CANONICAL_NAME_INBOX_CATEGORY_PRIMARY
に変わることになります。

GmailContractクラスの最新版(?)は
https://developers.google.com/gmail/android/
の "To see an example of this API in action, check out the sample app." からダウンロードしました。

GmailUnreadCounter Widget 2というウィジェットアプリを公開しているので、対応しておきました。
https://play.google.com/store/apps/details?id=net.madroom.gucw2
https://github.com/mp-android/GmailUnreadCounterWidget2/blob/master/src/net/madroom/gucw2/TranslucentActivity.java

August 15, 2013

GruntでCoffeeScriptとSCSSのファイルを監視して自動コンパイルしてみる

Grunt公式: http://gruntjs.com/

1. grunt-cliのインストール
$ npm install -g grunt-cli
2. 作業ディレクトリの作成
$ mkdir grunt_test
$ cd grunt_test
3. package.jsonの作成
vim package.json
4. package.json
{
  "name": "my-project-name",
  "version": "0.1.0",
  "devDependencies": {
  }
}
5. gruntと必要なプラグインのインストール
$ npm install grunt grunt-contrib-watch grunt-contrib-coffee grunt-contrib-sass --save-dev
* --save-devオプションをつけるとpackage.jsonの"devDependencies"を上書きしてくれるみたいです。
* "description"とか書いてないので警告が出ます。
* grunt-contrib-watch: https://github.com/gruntjs/grunt-contrib-watch
* grunt-contrib-coffee: https://github.com/gruntjs/grunt-contrib-coffee
* grunt-contrib-sass: https://github.com/gruntjs/grunt-contrib-sass

6. Gruntfile.jsの作成
$ vim Gruntfile.js
7. Gruntfile.js
module.exports = function(grunt) {
    grunt.initConfig({
        pkg: grunt.file.readJSON('package.json'),
        coffee: {
            compile: {
                expand: true,
                flatten: true,
                src: ['coffee/*.coffee'],
                dest: 'js',
                ext: '.js'
            }
        },
        sass: {
            compile: {
                expand: true,
                flatten: true,
                src: ['scss/*.scss'],
                dest: 'css',
                ext: '.css'
            }
        },
        watch: {
            coffee: {
                files: ['coffee/*.coffee'],
                tasks: ['coffee']
            },
            sass: {
                files: ['scss/*.scss'],
                tasks: ['sass']
            }
        }
    });
    grunt.loadNpmTasks('grunt-contrib-watch');
    grunt.loadNpmTasks('grunt-contrib-coffee');
    grunt.loadNpmTasks('grunt-contrib-sass');
    grunt.registerTask('default', ['coffee', 'sass']);
};
8. 監視開始
$ mkdir coffee
$ touch coffee/hello.coffee
$ mkdir scss
$ touch scss/test.scss
$ grunt watch
Running "watch" task
Waiting...
9. coffee/hello.coffeeを編集
console.log 'hello'
10. コンパイルされたファイルを確認
$ more js/hello.js 
(function() {
  console.log('hello');

}).call(this);
11. scss/test.scssを編集
#main {
  h1{ margin: 10px }
  p{ font-size: 90% }
}
12. コンパイルされたファイルを確認
$ more css/test.css 
#main h1 {
  margin: 10px; }
#main p {
  font-size: 90%; }

npmでCoffeeScriptをインストールしてコンパイルしてみるメモ

メモです。
# CoffeeScriptのインストール
$ npm install -g coffee-script

# hello.coffeeの作成
$ mkdir coffee
$ cd coffee
$ vim hello.coffee

# hello.coffeeに以下を記述
console.log 'hello'

# コンパイルと内容の確認
$ coffee -c hello.coffee
$ more hello.js
// Generated by CoffeeScript 1.6.3
(function() {
  console.log('hello');

}).call(this);

# ヘルプコマンドを実行
$ coffee -h

Usage: coffee [options] path/to/script.coffee -- [args]

If called without options, `coffee` will run your script.

  -b, --bare         compile without a top-level function wrapper
  -c, --compile      compile to JavaScript and save as .js files
  -e, --eval         pass a string from the command line as input
  -h, --help         display this help message
  -i, --interactive  run an interactive CoffeeScript REPL
  -j, --join         concatenate the source CoffeeScript before compiling
  -m, --map          generate source map and save as .map files
  -n, --nodes        print out the parse tree that the parser produces
   --nodejs       pass options directly to the "node" binary
  -o, --output       set the output directory for compiled JavaScript
  -p, --print        print out the compiled JavaScript
  -s, --stdio        listen for and compile scripts over stdio
  -l, --literate     treat stdio as literate style coffee-script
  -t, --tokens       print out the tokens that the lexer/rewriter produce
  -v, --version      display the version number
  -w, --watch        watch scripts for changes and rerun commands
変更の監視は
$ coffee -wc *.coffee
で出来ました。

gemでsassをインストールしてコンパイルしてみるメモ

メモです。
# sassのインストール(compassでまとめてインストールしてみます)
$ gem install compass

# test.scssの作成
$ mkdir scss
$ cd scss
$ vim test.scss

# test.scssに以下を記述
#main{
 h1{ margin-bottom: 20px }
 p{ font-size:90% }
}

# コンパイルと内容の確認
$ scss test.scss test.css
$ more test.css 
#main h1 {
  margin-bottom: 20px; }
#main p {
  font-size: 90%; }

# ヘルプコマンドを実行
$ scss -h
Usage: scss [options] [INPUT] [OUTPUT]

Description:
  Converts SCSS or Sass files to CSS.

Options:
    -s, --stdin                      Read input from standard input instead of an input file
        --trace                      Show a full traceback on error
        --unix-newlines              Use Unix-style newlines in written files.
        --sass                       Use the Indented syntax.
        --watch                      Watch files or directories for changes.
                                     The location of the generated CSS can be set using a colon:
                                       scss --watch input.scss:output.css
                                       scss --watch input-dir:output-dir
        --update                     Compile files or directories to CSS.
                                     Locations are set like --watch.
        --stop-on-error              If a file fails to compile, exit immediately.
                                     Only meaningful for --watch and --update.
        --poll                       Check for file changes manually, rather than relying on the OS.
                                     Only meaningful for --watch.
    -f, --force                      Recompile all Sass files, even if the CSS file is newer.
                                     Only meaningful for --update.
    -c, --check                      Just check syntax, don't evaluate.
    -t, --style NAME                 Output style. Can be nested (default), compact, compressed, or expanded.
        --precision NUMBER_OF_DIGITS How many digits of precision to use when outputting decimal numbers. Defaults to 3.
    -q, --quiet                      Silence warnings and status messages during compilation.
        --compass                    Make Compass imports available and load project configuration.
    -g, --debug-info                 Emit extra information in the generated CSS that can be used by the FireSass Firebug plugin.
    -l, --line-numbers               Emit comments in the generated CSS indicating the corresponding source line.
        --line-comments
    -i, --interactive                Run an interactive SassScript shell.
    -I, --load-path PATH             Add a sass import path.
    -r, --require LIB                Require a Ruby library before running Sass.
        --cache-location PATH        The path to put cached Sass files. Defaults to .sass-cache.
    -C, --no-cache                   Don't cache to sassc files.
    -E encoding                      Specify the default encoding for Sass files.
    -?, -h, --help                   Show this message
    -v, --version                    Print version
変更の監視は
$ scss -w *.scss
で出来ました。

Railsでscaffoldを実行してみる

今までRubyは開発系のツールで少し触っていた程度でしたが、今後、Railsも触っていく必要が出てきたので、とりあえずScaffold(とマイグレーション)を実行してブラウザからアクセスしてみるまでのメモです。
# railsアプリケーションの初期化
$ rails new rails_example

# scaffoldの実行
$ cd rails_example
$ rails generate scaffold User name:string email:string

# マイグレーションの実行
$ rake db:migrate
ソースを反映(デプロイ)して、ブラウザから /users にアクセス


ルーティングの一覧は、以下のコマンドで確認できました。
$ rake routes
   Prefix Verb   URI Pattern               Controller#Action
    users GET    /users(.:format)          users#index
          POST   /users(.:format)          users#create
 new_user GET    /users/new(.:format)      users#new
edit_user GET    /users/:id/edit(.:format) users#edit
     user GET    /users/:id(.:format)      users#show
          PATCH  /users/:id(.:format)      users#update
          PUT    /users/:id(.:format)      users#update
          DELETE /users/:id(.:format)      users#destroy
Chef + VagrantでApache + Passengerの環境構築に時間がかかりすぎた。。。

August 14, 2013

TextMate2の設定ファイルメモ

グローバルな設定ファィルと思われるファイルが
/Users/admin/Library/Application Support/TextMate/Global.tmProperties
にありました。

ユーザ設定ファイルは
~/.tm_properties
として作成できるみたいです。
参考: https://gist.github.com/dvessel/1478685

でも
http://madroom-project.blogspot.jp/2013/08/textmate2.html
の内容は、どちらに書いても反応しませんでした。

まあ、大した内容ではないですが、PCの乗り換え時とかには知っておくと良いかも。。。

TextMate2でサイドバーを左にするメモ

以下のコマンドで出来ました。
defaults write com.macromates.TextMate.preview fileBrowserPlacement left
参考: https://github.com/textmate/textmate/issues/699#issuecomment-19202919

August 13, 2013

Macの言語設定は日本語のままでiTunesを常に英語で起動するメモ

Language Switcherを使うと簡単にできます。
http://www.tj-hd.co.uk/en-gb/languageswitcher/

iTunesを選択、英語を選択して、"常にこの言語で起動"をクリックすれば完了です。

前からそうしていたのですが、HDDをSSDに変えたついでのメモでした。
(言語設定が日本語だと、購入した曲に付くカタカナ曲名とか日本語読み仮名とか、糞なので。。。)

August 10, 2013

Macでvagrant upが進まない

再現手順とかよくわかってないんですが、Macにて、ssh周りが原因で、以下の状態から進まなくなることがたまに発生します。
$ vagrant up
Bringing machine 'default' up with 'virtualbox' provider...
[default] Importing base box 'ubuntu1304'...
[default] Matching MAC address for NAT networking...
[default] Setting the name of the VM...
[default] Clearing any previously set forwarded ports...
[default] Creating shared folders metadata...
[default] Clearing any previously set network interfaces...
[default] Preparing network interfaces based on configuration...
[default] Forwarding ports...
[default] -- 22 => 2222 (adapter 1)
[default] -- 80 => 8080 (adapter 1)
[default] Booting VM...
[default] Waiting for VM to boot. This can take a few minutes.
http://qiita.com/gyhino@github/items/8c10249019cf1e9fce34 を参考にさせて頂き
$ sudo rm ~/.vagrant.d/insecure_private_key
すると進むようになりました。

August 4, 2013

Vagrant + ChefでオレオレPHP開発環境を作ってみました

追記:
依存レシピの管理はBerkshelfを使うべきと思いますが、とりあえずGitのサブモジュールにしてしまっています。

使用するIPアドレスとポートが"192.168.33.10"から"localhost:8081"(php5.5ブランチ)と"localhost:8080"(masterブランチ)に変わりました。記事内の各所は適宜置換して下さい。

--

レポジトリは https://github.com/mp-php/vagrant-phpdev-ubuntu です。

主な環境は
* PHP5.5
* Apache2.4
* MySQL5.5
です。MySQLのrootユーザのパスワードはデフォルトだと"root"になります。これは cookbooks/chef.json で変更できます。

以下、READMEの通りですが、大まかな流れを書いておきます。

まず git clone して vagrant up します。初回は結構時間がかかります。
$ git clone --recursive https://github.com/mp-php/vagrant-phpdev-ubuntu.git
$ cd vagrant-phpdev-ubuntu/
$ vagrant up
起動後、ホストOS側の"share"ディレクトリとゲストOS側の"/share"ディレクトリが共有されます。

新しいプロジェクトを作成するには、ホストOS側の"share"ディレクトリの中に、そのプロジェクトのディレクトリを作ります。
$ mkdir share/my_first_workspace
$ vim share/my_first_workspace/index.php

<?php
phpinfo();
vagrant ssh 等でゲストOSに入って
$ sudo ln -s /share/my_first_workspace /var/www/my_first_workspace
して、シンボリックリンクを貼ります。

これで http://192.168.33.10/my_first_workspace/ のようにアクセスして正しく表示されればOKです。

mod_rewriteを有効にしてあるので、各プロジェクトで .htaccess が使えるはずで、バーチャルホストの設定をしなくてもとりあえず動かせるかなーと。

その他の機能として
* phpMyAdmin http://192.168.33.10/phpmyadmin/
* DBDocs http://192.168.33.10/dbdocs/ (ちゃっかり入れてますw)
* phpunit コマンド
* apigen コマンド
* php-cs-fixer コマンド
* jsduck コマンド
が入っています。

DBDocsは、試しに http://192.168.33.10/dbdocs/index/generate から MySQL を選択
* Document name … 適当
* Description … 適当
* Host … localhost
* Database … phpmyadmin
* user … root
* password … root
* Charset … utf8
と入力して"Generate"ボタンを押してみて下さい。phpmyadminのテーブル一覧が生成されます。

開発上必要なパッケージがスカスカで足りないと思いますが、随時付け足していこうと思います。

良かったら使ってみて下さい。

August 3, 2013

chef-soloとknife-soloでPHP開発環境を構築するレシピを書いてみた

2013/08/04 追記
Vagrant用のレポを作りました。
https://github.com/mp-php/vagrant-phpdev-ubuntu
http://madroom-project.blogspot.jp/2013/08/chef-solophp.html

https://github.com/mp-php/chef-phpdev-ubuntu
は後日削除するかもしれませんm(_ _)m

--

chef-soloの学習がてら、PHP開発環境を構築するレシピを書いてみました。
https://github.com/mp-php/chef-phpdev-ubuntu

細かなパッケージはまだスカスカなので、ブランチは"pre-master"としています。暫く様子を見ながら使っていき、そのうち"master"として1コミットにまとめようかなと思います。

PHPは http://ppa.launchpad.net/ondrej/php5/ubuntu (今日現在、5.5.1)
apache2は http://ppa.launchpad.net/ondrej/apache2/ubuntu (今日現在、2.4.6)
からインストールしていて、MySQLは標準レポジトリからインストールしています。rootのパスワードはデフォルトだとrootになります。

NginxではなくApacheなのは、複数プロジェクトをまとめて動かす場合に.htaccessを使えた方が、サブディレクトリ型のURLで扱いやすいかなという理由です。

その他、開発の補助ツールとして、とりあえず
* phpMyAdmin (/phpmyadmin でアクセスできます。)
* fuel-dbdocs (/dbdocs でアクセスできます。)
* jsduck (jsduck コマンドが使えます。)
* PHPUnit (phpunit コマンドが使えます。)
* ApiGen (apigen コマンドが使えます。)
* PHP-CS-Fixer (php-cs-fixer コマンドが使えます。)
を入れてみました。

このレシピをサブモジュール管理した、Vagrant用のレポって作れるのかなー。作ったら、細かな使い方とか、改めて書きたいと思います。