2010年9月13日 #php #php

kohanaというphpフレームワークを触り始めました。MVCパターンなのでいろんなところで結構Railsと似ていますが、コード量が明らかにRailsより多くてまだ慣れてません。さすがにRailsやってから他の言語やフレームワークを触るとキツイです。

kohanaにはデフォルトでmodulesにuserguideが付いてます。ローカルでもガイドのドキュメントやAPIを参照できるため結構便利です。

userguideモジュールをアクティブする方法

bootstrap.phpの中に'userguide'を検索してコメントアウトします。

アクセスURL

例えばbase_urlが'myapp'の場合は:
http://localhost/myapp/userguide/docs
になります。

内容としては公式サイトのhttp://kohanaframework.org/guide/about.kohanaと同じになります。

2010年9月10日 #github

プロジェクトに検索機能を追加しようとする。

git checkout -b add-search
=> ブランチ'add-search'を作成し、それに乗換

// ファイル修正

git add .
git commit -am "Done"
=> 修正ファイルをコミット、コミットメッセージは"Done"

git checkout master
=> masterブランチに乗換

git merge add-search
=> add-searchでの修正内容をマージ

git push
=> サーバにpush

2010年8月20日

Rails: default_scopeを使った場合注意しておきたいことArticleモデルがあるとします。ブログの記事は普通最新の順番で並んでまのでこんなdefault_scopeを定義したかもしれません。

# in Article model
default_scope :order => "articles.created_at DESC"

これで普通にArticle.allとかfindのときはデフォルトで作成日時が最新のものから並びますが
Article.firstとArticle.lastにも影響があります。
つまり

Article.first # <Article id:999, ...>
Article.last  # <Article id:1, ..>

考えてみれば当たり前のことですが、念のため覚えておきましょう。

2010年8月15日

PostとCommentのModelがあってPostが複数のCommentを持ってます。やりたいのはPostの表示画面(show view)でCommentを削除するリンクを作成ことです。

前提

まずPostとCommentのModel、及びroutes.rbの設定を理解しましょう。

# post model
has_many :comments

# comment model
belongs_to :post

# routes.rb
resources :posts do
  resources :comments
end

方法

Viewのerbファイルでは下記のようなリンクを作成します。

<% @article.comments.each do |comment|
  <%= comment.content %>
  <%= link_to "Delete", article_comment_path(@article, :comment_id => comment), :method => :delete %>
<% end %>

これはcomments_controllerのdestroyアクションを呼ぶのでdestroy actionを作成する必要があります。

# in comments_controller.rb

def destroy
  comment = Comment.find(params[:comment_id]
  comment.destroy
  redirect_to request.referer
end

:comment_idはviewで設定するパラメータ名と一致すればOKです。

2010年8月 8日

Userモデルにどのカラムを定義したっけ、と言う場合schema.rbをいちいちチェックしないで済む方法があります。それがCarlos Brando氏が作ってくれたRuby on RailsのTextMate Bundleです。

出来る事

これは元々のDr. Nic氏のruby-on-rails-tmbundleをForkして作ったものなので、従来の機能は保ちつつ新しい便利な機能が追加されました。

Alt(Option) + Space

例えばUserモデルの変数user, @user, @@userなどの後ろでAlt(Option) + Spaceを押すと利用可能な属性がリストされます。なかなか便利です。

インストール

mkdir -p ~/Library/Application\ Support/TextMate/Bundles

cd ~/Library/Application\ Support/TextMate/Bundles

git clone git://github.com/carlosbrando/ruby-on-rails-tmbundle.git "Ruby on Rails.tmbundle"

osascript -e 'tell app "TextMate" to reload bundles'

本家サイト:http://github.com/carlosbrando/ruby-on-rails-tmbundle

2010年8月 6日

(...)で正規表現をグループ化し、後でマッチしたものを\1、\2で呼び出したい時はぜひシングルクオーテーションとダブルクオーテーションに注意。
この場合はシングルクオーテーションを使ってください。

"hello".gsub(/([aeiou])/, '<\1>')         #=> "h<e>ll<o>"
"hello".gsub(/([aeiou])/, "<\1>")         #=> "h< >ll< >"

ここは括弧が付いてるからマッチしたものは\1で呼び出せます。そしてマッチの規則はa,e,i,o,uのいずれかです。なので"hello"の中の"e"と"o"が置換されました。

秀丸でやったときはダブルクオーテーションも大丈夫だっだ。。。

2010年8月 2日

WordPressブログにFacebookのLikeボタンを追加しましたので、メモとして取っておきます。

手順

Like Button for Web - Documentation - Facebook for Developersでリンクコードを取得

  • Layout Stylebutton_count
  • Width90に。
  • Get Codeで貼り付けるコードを取得

WordPress記事リンクを組み立て

各ページごとにLikeボタンが欲しいので、こんなファンクションを作りました。中のiframeのソースはFacebookから取得したコードで、修正したのが2点あります。

  • href=のURLをget_permalink()で取れた記事のURLに置き換えます。
  • margin-bottom:-8pxでレイアウトの調整を行ないます。
// facebook like button
function fbLike() {
  $link = get_permalink();
  echo "
  <iframe src='http://www.facebook.com/plugins/like.php?href=".$link."&amp;layout=button_count&amp;show_faces=true&amp;width=90&amp;action=like&amp;colorscheme=light&amp;height=21' scrolling='no' frameborder='0' style='border:none; overflow:hidden; width:90px; height:21px;margin-bottom:-8px;' allowTransparency='true'></iframe>
    ";
}

後はfbLike()を読んだだけでLikeボタンが表示されます。

2010年7月29日 #rails

This is about how to customize the url to the form like "id + post.title", which can be simply overriding the* to_param* method in your model class.

Here is the example.

  class Person
    def to_param
      "#{id}-#{name.parameterize}"
    end
  end

  @person = Person.find(1)
  # => #<Person id: 1, name: "Donald E. Knuth">

  <%= link_to(@person.name, person_path(@person)) %>
  # => <a href="/person/1-donald-e-knuth">Donald E. Knuth</a>

The parameterize is a method that replaces special characters in a string so that it may be used as part of a ‘pretty’ URL.
Rails is smart enough to extract this back into the plain id when you access your controller action.
You can access the url '/person/1-kinopyo' or '/person/1', both ok.

If you want to know more, here is a good article: http://augustl.heroku.com/blog/styling-rails-urls.

日本語

slugはurlをより綺麗に表示するためのものです。例えばこの記事のpermanent urlは"rails-id-slug-name-in-url"にしています。英語世界になるんですが、これのようにurlを見ただけでそのurl先の内容が大体わかるようにするのがslugです。

この記事ではRailsで"id + post.title"のような形のURLを作る方法を紹介します。

方法

モデルクラス内にto_paramメソッドをオーバーライドするだけです。
例として

  class Person
    def to_param
      "#{id}-#{name.parameterize}"
    end
  end

  #controller
  @person = Person.find(1)
  # => #<Person id: 1, name: "Donald E. Knuth">

  #view
  <%= link_to(@person.name, person_path(@person)) %>
  # => <a href="/person/1-donald-e-knuth">Donald E. Knuth</a>

上記のようにmodelクラスを修正するだけで、他の影響はないです。URL: '/person/1-kinopyo'と'/person/1'はどっちでも使えます。
parameterizeはRailsのビルトインのメソッドでurlに使う文字列に変換してくれるんです。しかし日本語などは完全にブランクに変換するので要注意です。

もしurlを"/person/kinopyo"のようにperson.nameにカスタムしたい場合はこれより少し複雑になります。興味のある方は下記リンク(英語)を参照してください。 http://augustl.heroku.com/blog/styling-rails-urls.