2011/09/29

RailsでFacebook認証

Gemfileに書きを追記

gem 'oauth'
gem 'facebook_oauth'
gem 'oauth2', '0.4.1'

なぜかoauthは0.4.1以上だと上手く行かなかったのでversionを指定します。あとは各種コントローラーを作ります。もちろん事前にデベロッパー登録はをしておいてCONSUMER_KEYなどは適宜取得したものに変更します。

app/controllers/users_controller.rb
class UsersController < ApplicationController

  CALLBACK_URL    = "http://localhost:3000/users/callback"
  CONSUMER_KEY    = "アプリID"
  CONSUMER_SECRET = "アプリの秘訣"

  def index
  end

  def oauth
    client = FacebookOAuth::Client.new(
      :application_id     => CONSUMER_KEY,
      :application_secret => CONSUMER_SECRET,
      :callback           => CALLBACK_URL
    )
    redirect_to client.authorize_url
  end

  def callback
    @client = FacebookOAuth::Client.new(
      :application_id     => CONSUMER_KEY,
      :application_secret => CONSUMER_SECRET,
      :callback           => CALLBACK_URL
    )
    @client.authorize(:code => params[:code])
  end
  
end
app/views/users/index.html.erb
<%= link_to 'OAuth認証', '/users/oauth' %>
app/views/users/callback.html.erb
<%= @client.me.info %>

http://localhost:3000/usersにアクセスすれば認証ページヘ行きます。

CakePHPでPaginatorの指定

コントローラーでは下記の通り
$this->paginate=array(
    'conditions' => array(検索条件),
    'fields' => array(取得するカラム),
    'page' => int(最初に表示するページ),
    'limit' => int(デフォルトは20),
    'sort' => string(ソートkey),
    'direction' => string(asc or desc)
    'recursive' => findAllに与える
 );
ビューではこんな感じ
  ' ',
 'after'=>' ',
 'modulus'=>3,
 'first'=>'',
 'last'=>'',
 'separator'=>'|',
 'class'=>'paging_inner'
 );
 echo $paginator->first('最初',array('after'=>' ','class'=>'paging_inner' )).
 $paginator->prev('<< '.__('前', true), array('class'=>'paging_inner' ), '最初',
 array('class'=>'disabled' )).
 $paginator->numbers($options).
 $paginator->next(__('次', true).' >>', array('class'=>'paging_inner' ), '最後',
 array('class'=>'disabled' )).
 $paginator->last('最後',array('before'=>' ','class'=>'paging_inner' ) );
 ?>

will_paginateのオプション

rails3に移行してkaminariを使っている人も多かも知れませんがwill_pagenateで各種パラメーターを変更する方法。

@@pagination_options = {
:class => 'pagination',
:prev_label => '&laquo; Previous',#前ページリンクの文言
:next_label => 'Next &raquo;',#次ページリンクの文言
:inner_window => 4,#現在ページと「...」の間のリンク数
:outer_window => 1,#「...」とnext_labelの間のリンク数
:separator => ' ', # リンク間の区切り文字
:param_name => :page, #ページ数のパラメーター名
:params => nil, #遷移先URLに付加するパラメーター
:renderer => 'WillPaginate::LinkRenderer',
:page_links => true,
:container => true
}
変更したい所でオーバーライドしてあげればOK

RubyでTwitter認証を使うと便利なtwitter-auth

twitter-authを使うと認証関連を全て受けおってくれます。

% script/generate twitter_auth

を実行するとconfig/twitter_auth.ymlが生成されるのでoauth_consumer_keyやoauth_consumer_secretやcallbackURLを記載します。loginとlogoutのパスは自動で生成されるのでそこにアクセスすると認証されるようになっています。

https://github.com/mbleigh/twitter-auth

2011/08/15

Railsでパンくずリスト

Railsでは簡単にパンくずリストを作れます。 Gemfileに下記の通り記載してbundle install
gem 'crummy'
パンくずリスト表示したい場所に下記の通り記載
<%= render_crumbs %>
あとはアクションで項目を追加していけます。
class ApplicationController < ActionController::Base
  add_crumb 'HOME', '/'
end

Mac Portsでのメンテナンス

MacPortsでは古いバージョンは削除されすにインアクティブにされるだけです。アクティブでないものを削除するには下記のコマンドを実行します。
sudo port uninstall -f inactive

ruby-debug19を使う

ruby-debug19を使うとデバッグの際に便利です。追加の仕方は下記の通り。 Gemfileに追加してbundle installのあとデバッグポイントにdebuggerと追加
gem "ruby-debug19"
あとはrails s --debugでサーバーを起動するとdebuggerと記載されたところで止まります。その後は下記のコマンドにて詳細を確認できます。

list : 周辺のソース表示
p 変数名 : 変数の中身を確認できます
cont : 次のbreakpointまで実行

Rails3でタイトルタグを動的に変える

まずはビューのタイトルタグで下記の用に変更
<%= content_for?(:title) ? yield(:title) : "デフォルトタイトル"%>
あとはタイトルを変えたいビューで書き換えてあげる
<% content_for :title do %>
書き換えたいタイトル
<% end %>

gitでコンフリクト

Gitでコンフリクトして、自動でマージできない場合は該当ファイルの一覧が表示されるのでそれを修正すればgit pushできるようになります。


こちらのコマンドでコンフリクトファイルの一覧が表示できます。
git ls-files -u

Railsでフラッシュメッセージ

Railsでエラー文言などのフラッシュメセージを表示させる方法 まずはビューでエラーメッセージを表示させたい所に
<%= flash[:notice] if flash[:notice] %>
コントローラーで文言を入れる
 flash[:notice] = "hogehoge"

2011/07/29

VimでのZencodingメモ

div#side>ul.localnav>li*3>a

こんな感じで打った後、Ctr+yとカンマ[,]を打つと展開されます。
参考: http://d.hatena.ne.jp/sakurako_s/20110126/1295988873

プラグイン自体のインストールは前の記事にも書いたvundleが便利です。
http://iiidevelop.blogspot.com/2011/07/vimvundle.html

Gitの初期設定


sudo yum install -y git
git config --global user.name "名前"
git config --global user.email メール@アドレス
git config --global color.ui true 

あとはgit add . なりgit commit -m "" なり git pushなりしてください。

CakePHPで個別にタイトルを変える

CakePHP1.3の方法は下記の通り

ビューでタイトルを入れる場所をつくる。
<?php echo $title_for_layout; ?>

コントローラーでタイトルを入れる。
$this->set('title_for_layout','hogehoge');

FacebookやTwitterの「いいね」ボタンの設置

それぞれ専用のページから取ってこれます。

http://twitter.com/goodies/tweetbutton

サンプル
<a class="twitter-share-button" data-count="horizontal" data-lang="ja" href="http://twitter.com/share">ツイート</a>
<script src="http://platform.twitter.com/widgets.js" type="text/javascript"></script>

http://developers.facebook.com/docs/reference/plugins/like/

サンプル
<div id="fb-root"></div>
<script src="http://connect.facebook.net/en_US/all.js#appId=256349884376536&amp;xfbml=1"></script>
<fb:like font="" href="" send="true" show_faces="true" width="450"></fb:like>

CakePHPのデバッグ

見たい変数をvar_dumpに入れればデバッグ表示されます。
var_dump($dump);

Virtualboxのハードディスクイメージのコピー

virtualboxのハードディスクイメージファイルvdiはIDを持っているので単純にコピーできません。ので専用のコマンドを使ってコピーします。

VBoxManage clonevdi コピーされる.vdi コピー先.vdi

ZendFrameworkのインストール

単純にインストールしてパスを通すだけで完了。

ダウンロードはこちらから
http://framework.zend.com/download/latest

php.iniの編集で
vi /etc/php.ini

/usr/local/lib/以下に作成した場合
include_path = “.:/usr/local/lib/php/ZendFramework/library”

apacheの再起動
/etc/init.d/httpd restart

参考:http://codezine.jp/article/detail/1824?p=2

MySQLのダンプ

下記の感じでOK
mysqldump --password='password' -A > dump.sql

戻すときはリダイレクトで。
mysql < ./dump.sql

MySQL自動データベースバック

バックアップスクリプトの作成
vi mysql-backup.sh

内容は下記の通り

#!/bin/bash

PATH=/usr/local/sbin:/usr/bin:/bin

# バックアップ先ディレクトリ
BACKDIR=/backup/mysql

# MySQLrootパスワード
ROOTPASS=xxxxxxxx

# バックアップ先ディレクトリ再作成
rm  -rf $BACKDIR
mkdir -p $BACKDIR

# データベース名取得
DBLIST=`ls -p /var/lib/mysql | grep / | tr -d /`

# データベースごとにバックアップ
for dbname in $DBLIST
do
    table_count=`mysql -u root -p$ROOTPASS -B -e "show tables" $dbname|wc -l`
    [ $table_count -ne 0 ] &&
    mysqlhotcopy $dbname -u root -p $ROOTPASS $BACKDIR | logger -t mysqlhotcopy
done

権限を変更してcronに設定。
chmod 700 mysql-backup.sh
echo "0 5 * * * root /root/mysql-backup.sh" > /etc/cron.d/backup 

参考:http://centossrv.com/mysql-backup.shtml

戻すときはディレクトリごとコピーする
/bin/cp -Rf /backup/mysql/test/ /var/lib/mysql/ 

vim-refの設定

こちらを参考に 
http://d.hatena.ne.jp/holypp/20110703/1309711799

w3mをインストールしてくる。

% sudo port install w3m

RubyリファレンスのDLと設定
wget http://doc.okkez.net/archives/201106/ruby-refm-1.9.2-dynamic-20110629.tar.gz
tar zxvf ruby-refm-1.9.2-dynamic-20110629.tar.gz
mv ruby-refm-1.9.2-dynamic-20110629 rubyrefm

sudo vi /opt/local/bin/refe

記載内容は下記な感じで。
#!/bin/sh
exec ruby -Ke -I ~/Documents/Reference/rubyrefm/bitclust/lib ~/Documents/Reference/rubyrefm/bitclust/bin/refe.rb -d ~/Documents/Reference/rubyrefm/db-1_8_7 "$@"

権限の変更
sudo chmod 755 /opt/local/bin/refe

Shift+kでリファレンスを参照できる

Vimプラグイン管理のvundleインストール

開発環境は基本Vimで行っています。IDEも便利ですが重いのと色々ごちゃごちゃしていて集中力が落ちるのであまり使っていません。 Vim使いの人はプラグインを入れるともっと便利になるのですがその管理ツールVundleのインストール方法です。

VundleはRubyのBundleにインスパイアされたとのことで、必要なVimプラグインを.vimrcに書くだけでインストールできる管理ツールです。(Gemfileに当たるのが.vimrcというイメージです)

早速インストール方法は下記を参照すればOK。
https://github.com/gmarik/vundle/blob/master/README.md 

gitからVundel本体をとってきます。

$ git clone http://github.com/gmarik/vundle.git ~/.vim/bundle/vundle

あとは.vimrcに下記のような感じで必要なプラグインを記載。

set nocompatible               " be iMproved
 filetype off                   " required!

 set rtp+=~/.vim/bundle/vundle/
 call vundle#rc()

 " let Vundle manage Vundle
 " required! 
 Bundle 'gmarik/vundle'

 " My Bundles here:
 "
 " original repos on github
 Bundle 'tpope/vim-fugitive'
 Bundle 'Lokaltog/vim-easymotion'
 Bundle 'rstacruz/sparkup', {'rtp': 'vim/'}
 " vim-scripts repos
 Bundle 'L9'
 Bundle 'FuzzyFinder'
 Bundle 'rails.vim'
 " non github repos
 Bundle 'git://git.wincent.com/command-t.git'
 " ...

 filetype plugin indent on     " required!  

Ruby使いであれば下記を追記しておくと便利です。

Bundle 'Shougo/neocomplcache'
Bundle 'Shougo/unite.vim'
Bundle 'thinca/vim-ref'
Bundle 'thinca/vim-quickrun'

"Ruby
Bundle 'rails.vim'

"Html
Bundle 'mattn/zencoding-vim'

これらの設定をした後はvimを起動して:BundleInstallでプラグインを一括でインストールできます。vim-refについては次の記事で設定をまとめます。

2011/07/28

Facebookのいいねの時に表示されるサムネイル画像


<meta property="og:image" content="IMAGE_URL"/>


って感じでメタタグに指定してあげればOK。ただしIMAGE_URLはフルパスで入れること。
入力項目は下記のツールで確認できる。

http://developers.facebook.com/tools/lint/

同様にog:title、og:type、og:urlなども指定できる。

RailsやCakePHPなどで動的に生成するにはレイアウトテンプレートに下記のように書いて
指定したいコントローラーなどでURLを追加すればOK。

<?php

if (!empty($imgurl)) {

echo '<meta property="og:image" content="http://hoge.com/img/'.$imgurl.'" />';

} else {

echo '<meta property="og:image" content="http://hoge.com/img/og_logo.jpg" />';

};

?>

2011/06/12

Rails3でwill_pagenateを使う

will_paginate 3.0.preだと下記のエラーが出るので3.0pre2を使う
DEPRECATION WARNING: railtie_name is deprecated and has no effect. 

Gemfileこんな感じで記入して後はbundle install
#gem 'will_paginate', '3.0.pre'
gem 'will_paginate', '3.0.pre2'

apacheの負荷テスト

ab [options] URL

でできる。
ServerLimit 及び MaxClients の設定の参考に。
参考:
http://www.atmarkit.co.jp/flinux/rensai/apache15/apache15b.html

apacheのエラー修正

PHP Warning:  PHP Startup: apc: Unable to initialize module\nModule 
compiled with module API=20050922, debug=0, thread-safety=0\nPHP
compiled with module API=20060613, debug=0, thread-safety=0\nThese 
options need to match\n in Unknown on line 0

こいつはhttp://forums.fedoraforum.org/archive/index.php/t-157117.htmlを参考に
yum install php-pear httpd-devel php-devel
pecl uninstall apc
pecl install apc
で対応

もう一つこっちは直したと思ったんだけど。libxml2を入れたけどlibxsltを入れたなかったのが原因っぽいので再度対応。参考:http://doruby.kbmj.com/tn_on_rails/20110311/CentOS_5.5_Nokogiri_
WARNING: Nokogiri was built against LibXML version 2.7.8, but has dynamically loaded 2.6.26

http://d.hatena.ne.jp/kitamomonga/20100223/ruby_nokogiri_install_with_any_libxml2_pathを参考にソースを入れてる適当なディレクトリに移動してから下記を実行。

tar xzvf LATEST_LIBXSLT
cd libxslt-1.1.26/
./configure --prefix=$HOME/usr/local --with-libxml-src=../libxml2-2.7.7
make
make install

em install nokogiri -- --with-xml2-include=$HOME/usr/local/include/libxml2 --with-xml2-lib=$HOME/usr/local/lib --with-xslt-dir=$HOME/usr/local

んでapacheを再起動。

mysqlのエラー修正

エラーの修正
[Warning] '--default-character-set' is deprecated 
and will be removed in a future release. 
Please use '--character-set-server' instead.
をはいていたのでmy.confを修正
[mysqld]
#default-character-set = utf8
character-set-server = utf8

もう一つのエラー
Can't open the mysql.plugin table. Please run mysql_upgrade to create it.
110612 14:43:49  InnoDB: Started; log sequence number 0 44446294

こっちは下記で修正
mysql_upgrade -u root -p

mysqlを再起動。

2011/04/16

db無しでwill_paginateを使う

コントローラーの方でコレクションを取得
page = params[:page]

will_paginateのインスタンスを作成
@page = @views.paginate({
  :page => params[:page], 
  :per_page => 10, 
  :total_entries => 100
})

あとはビューの方はこんな感じ
<div id ="paging">
  <%= will_paginate @page %>
<br />

Dropboxでgit管理

まずはフォルダ作成
$ cd ~/Dropbox/
$ mkdir Repos
$ cd Repos
プロジェクト作成
$ mkdir sample.git
$ cd sample.git
$ git --bare init
んでプロジェクトフォルダでpush
cd ~/dev/old_prj
git init
git add .
git commit
git push ~/Dropbox/repo/sample.git master
git remote add origin ~/Dropbox/repo/sample.git

参考:
http://naoki.sato.name/lab/archives/38

RVMで複数のRubyやRails環境

まずはgitでインストール
% git clone git://github.com/wayneeseguin/rvm.git
$ cd rvm
$ ./install
.bash_profileに以下を記入
[[ -s "$HOME/.rvm/scripts/rvm" ]] && source "$HOME/.rvm/scripts/rvm"

あとはRubyなりRailをガシガシ入れる(以下は一例)
% rvm list known
$ rvm install 1.8.7
$ rvm install 1.9.2
$ rvm gemset create rails2
$ rvm use 1.8.7@rails2
$ rvm gemset create rails3
$ rvm use 1.9.2@rails3
$ gem install rails

使いたいバージョンを切り替えるときは次のコマンド
%rvm use ruby-1.9.2@rails3

メッセージが結構ちゃんと親切に表示されるので詰まったらメッセージをちゃんと読んでみよう。

参考:
http://curiosity-drives.me/programming/rails/rvm_ruby_rails/

MacPortで入れたMySQLの自動起動設定

MacPortsで入れたMySQLの自動起動設定。システム環境設定からやる方法もあるけどこっちの方が好き。
MacOS 10.6.7環境
$ sudo mkdir -p /opt/local/etc/LaunchDaemons/org.macports.mysql5
$ cd /opt/local/etc/LaunchDaemons/org.macports.mysql5
$ sudo curl -O http://robwilkerson.org/_resources/hotlink/blog/mysql5.wrapper
$ sudo curl -O http://robwilkerson.org/_resources/hotlink/blog/org.macports.mysql5.plist
$ sudo chown root:wheel /opt/local/etc/LaunchDaemons/org.macports.mysql5/*
$ sudo chmod 755 /opt/local/etc/LaunchDaemons/org.macports.mysql5/mysql5.wrapper
$ sudo chmod 644 /opt/local/etc/LaunchDaemons/org.macports.mysql5/org.macports.mysql5.plist
$ sudo ln -s /opt/local/etc/LaunchDaemons/org.macports.mysql5/org.macports.mysql5.plist /Library/LaunchDaemons/org.macports.mysql5.plist

参考:
http://d.hatena.ne.jp/solitary_shell/20100107/1262874052

herokuでGmail設定

まずはプラグインの導入
$ ruby script/plugin install git://github.com/collectiveidea/action_mailer_optional_tls.git

config/email.ymlに下記を記入
production:
  delivery_method: :smtp
  smtp_settings:
    tls: true
    address: "smtp.gmail.com"
    port: 587
    domain: "smtp.gmail.com"
    authentication: :plain
    user_name: "your_email@gmail.com"
    password: "your_password"

これだけで動くはず。ほかのプラグイン(gmail_smtpとか)もいれちゃったりするとうまく動かないので注意(これで嵌った)

参考:
http://d.hatena.ne.jp/rx7/20100526/p1

herokuでタイムゾーンの設定

herokuの環境ができている前提で
heroku config:add TZ=Asia/Tokyo

2011/03/05

Serversmanのwordpressインストール

mysqlのインストール
yum install -y mysql mysql-server

文字コードの設定
vim /etc/my.cnf
下記を追記
default-character-set=utf8

MySQLを再起動、起動設定
/etc/rc.d/init.d/mysqld start
chkconfig mysqld on

DBの作成(MySQLで)
create database wordpress;
grant all privileges on wordpress.* to wordpress@localhost identified by 'パスワード';

Worpressをダウンロードして、解凍、設定(DBの設定は作ったDBの設定を入力)
wget http://ja.wordpress.org/wordpress-3.1-ja.zip
unzip wordpress-3.1-ja.zip
mv wordpress-3.1-ja /var/www/
chown -R apache:apache /var/www/wordpress/
cp /var/www/wordpress/wp-config-sample.php /var/www/wordpress/wp-config.php
vim /var/www/wordpress/wp-config.php

あとはSendmainlのインストールと起動設定
yum install sendmail
/etc/rc.d/init.d/sendmail start
chkconfig sendmail on

ServersmanのSSH初期設定

まずは接続
ssh root@xxx.xxx.xxx.xxx -p ポート番号
パスワードを入力で接続OK

バージョンを更新
yum update
新しいユーザーを作成してログインを許可
useradd user
passwd user
vim /etc/group
wheel::10:root,user
rootでのログインをなしに
vim /etc/ssh/sshd_config
PermitRootLogin no
AllowUsers user
SSHの再起動
/etc/init.d/sshd restart
exit
参考:http://d.hatena.ne.jp/deeeki/20100530/serversman_user_ssh

2011/02/27

MacPortsで入れたmysqlの文字化け

MacPortsで入れたmysqlがnavicatやphpadminなどで文字化けする場合
my.cnfで文字コード指定をしてやる必要があります。
まず最初にmy.cnfがない場合はコピーしてきます。
sudo cp /opt/local/share/mysql5/mysql/my-small.cnf /opt/local/etc/mysql5/my.cnf
んでできたmy.cnfに下記の設定
sudo vi /opt/local/etc/mysql5/my.cnf
[mysqld]
default-character-set = utf8
skip-character-set-client-handshake
あとはmysqlの再起動。

それでも文字化けが出るようであればnavicatやphpadminの設定確認。
該当するdatabaseを右クリックしてdatabase propertiesを確認。

2011/02/15

Google Analytics API

Google AnalyticsはAPIを公開しているのでアクセスログを定期的に出力したりできます。
こんな感じ。

<?php
require_once 'googleanalytics.class.php';
try {
    // アカウント情報を設定
    $ga = new GoogleAnalytics('ID','PASS');

    // プロファイルIDを指定
    $ga->setProfile('ga:プロファイルID');

    // 期間を指定
    $yesterday = date("Y-m-d",strtotime("-1 day"));
    $lastweek = date("Y-m-d",strtotime("-1 week"));
    $ga->setDateRange($lastweek,$yesterday);

    // 日付別の総ページビューを取得
    $report = $ga->getReport(
        array(
            'dimensions'=>urlencode('ga:date'),
        'metrics'=>urlencode('ga:pageviews,ga:visits'),
            'sort'=>'ga:date'
        )
    );

    // 結果を出力
    $result = print_r($report, TRUE);

   // 件名
   $subject = 'GoogleAnalytics{$yesterday}';
   // 本文
   $mailbody = '{$result}';
   // メール送信
   mb_send_mail("宛先",$subject,$mailbody);

// 例外処理
} catch (Exception $e) {
    print 'Error: ' . $e->getMessage();
}

?>
googleanalytics.class.phpと参考情報は下記から
http://www.askaboutphp.com/63/google-analytics-api-class-for-php.html

2011/02/01

Ruby1.8.7 tlsmailを使う

rubyでgmail送信を行うにはtlsmailを使うのが楽です。
# -*- coding: utf-8 -*-
require "rubygems"
require "tlsmail"
require "time"

Net::SMTP.enable_tls(OpenSSL::SSL::VERIFY_NONE)
Net::SMTP.start("smtp.gmail.com", "587", "localhost", "Gmailアカウント", "パスワード", :plain) do |smtp|
  smtp.send_message msg, "送信元アドレス", "送信先アドレス"
end
メッセージの中身(msg)は下記のように指定

msg =<<EOF
From: xxx@gmail.com
To: xxx@xxx.jp
Subject: TEST
Date: #{Time.now.rfc2822}

TEST
\r\n
EOF
ちなみに
コマンド文字列および正規表現の中では#{式}という形式で式の内容(を文字列化したもの)を埋め込むことができます。
http://www.ruby-lang.org/ja/man/html/_A5EAA5C6A5E9A5EB.html#a.bc.b0.c5.b8.b3.ab

($ruby = "RUBY"の場合)



   "my name is #{$ruby}" #=> "my name is RUBY"

#{Time.now.rfc2822}の部分ね。

2月2日 追記
ちなみに本文になにか変数を入れたい場合tmailを使う方法もある。
tmailはメールの箱だけ用意するってイメージで、その場合は下記のとおり。
require 'tmail'
require "tlsmail"

    # tmailでメールを作成
    mail = TMail::Mail.new
    mail.to = ''
    mail.from = ''
    mail.subject = 
    mail.date = Time.now
    mail.mime_version = '1.0'
    mail.set_content_type 'text', 'plain', {'charset'=>'utf-8'}
    mail.body = result.items

    # メールはNet::SMTPで送信。
    Net::SMTP.enable_tls(OpenSSL::SSL::VERIFY_NONE)
    Net::SMTP.start( "smtp.gmail.com",  587, "localhost.localdomain", "", "", "plain"){ |smtp| 
         smtp.sendmail(mail.encoded, mail.from, mail.to)