Kinopyo Blog

プログラマとしてRuby, Rails, iPhone, iPad,Macなどなどと向き合う日々のログポース

Archive for 14:51

(English) Ruby: Build and use native C/C++ extensions such as RedCloth on Windows

2010年08月30日

申し訳ありません、このコンテンツはただ今 English のみです。

Rails3 WillPaginateをカスタマイズ、CSSを適用

2010年08月25日

目標

http://mislav.uniqpath.com/will_paginate/のようなCSSを適用し、スタイリングする。

このCSSはwill_paginateのgh-pages treeからダウンロードできます。

will_paginate_style

バージョン

Rails: 3.0.0.rc1

will_paginate: 3.0.pre2

方法

例えばダウンロードしたCSSの中のdigg_paginationを適用するとします。

その場合はこの生成されたpaginateのdivのclassを”digg_pagination”に設定すればOKです。

実現する方法としては二つあります。

viewにハードコーディング
<%= will_paginate @articles, :class => "digg_pagination" %>
グローバルで設定する

例えばconfig/initializers/will_paginate.rbというファイルを作り下記のように設定します。

WillPaginate::ViewHelpers::pagination_options[:class] = "digg_pagination"

これを設定した後はサーバを再起動する必要があります。

ちょっとした問題

今の時点でのwill_paginateは該当ページの要素をemとして生成しclassは何も指定していないです。

<div class="digg_pagination">
  <span class="previous_page disabled">Previous</span>
  <em>1</em>
  <a ...>2</a>
  ......
</div>

しかしCSSではcurrentというclassでスタイリングを行ってます。なのでどうやらこのemをspanに変更しclass=”current”に変更する必要があります。方法としてはwill_paginateのあるメソッドをオーバーライドします。

will_paginateのRDOCをよく見るとPaginationListLinkRendererクラス内のpage_numberというメソッドが修正のターゲットになります。なので下記のようなクラスを作成ます。

class PaginationListLinkRenderer < WillPaginate::ViewHelpers::LinkRenderer

  protected

  def page_number(page)
    unless == current_page
      link(page, page, :rel => rel_value(page))
    else
      # tag(:em, page)
      tag(:span, page, :class => "current")
    end
  end

end

コメントアウトされたのがそもそものコードです。

次はこのクラスをrequireしてwill_paginateのoptionに指定すればOKです。

requireが必要なクラスは私は全部config/initializers/custom_requires.rbにまとめて書いてます。

# in config/initializers/custom_requires.rb
require 'lib/pagination_list_link_renderer'

# in config/initializers/will_paginate.rb
WillPaginate::ViewHelpers.pagination_options[:render] = "PaginationListLinkRenderer"

これで完了です。

リンク

will_paginateのgithubページ

will_paginateのcssダウンロード

大変参考になった記事(英語)

Rails: requestがAjaxかどうかを判断するには

2010年08月22日

requestがajaxかどうかを判断するのは、とても簡単です。


# in controller
if request.xhr?
  ...
end

xhrはXMLHttpRequestの略称です。XHRについては下記の記事を参照してください。

今更のAjax基本:XMLHttpRequestについて

Rails: default_scopeを使った場合注意しておきたいこと

2010年08月20日

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, ..>

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

Rails: Nested Resoucesを削除するには

2010年08月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です。

Rails: モデルクラスのプロパティをAlt+Spaceで呼び出せるTextMate Bundle

2010年08月08日

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

[Ruby]正規表現をグループ化し、マッチしたものを置換したい場合はシングルクオーテーションを

2010年08月06日

(…)で正規表現をグループ化し、後でマッチしたものを\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年08月05日

申し訳ありません、このコンテンツはただ今 中文 のみです。

[Rails]deprecated Rails::Application警告を避ける方法

2010年08月04日

Rails3をbeta4からRCにアップグレードしたら、こんな警告が出続けました。



DEPRECATION WARNING: Calling a method in Rails::Application is deprecated, please call it directly in your application constant MyApp:Application.

解決方法

Rakefileを修正しRails:Applicaitonを[ProjectName]::Applicaitonに書き換えればOKです。

例えば自分のプロジェクト名がMyappの場合は下記になります。

require File.expand_path('../config/application', __FILE__)
require 'rake'

Myapp::Application.load_tasks

WordPressブログにFacebook Likeボタンを追加しました

2010年08月02日

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

手順

Like Button – Facebook開発者でリンクコードを取得
  • 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."&layout=button_count&show_faces=true&width=90&action=like&colorscheme=light&height=21' scrolling='no' frameborder='0' style='border:none; overflow:hidden; width:90px; height:21px;margin-bottom:-8px;' allowTransparency='true'></iframe>
		";

}

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