Kinopyo's Blog

I love this game.

Posts Tagged ‘rails’

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

[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

TextMate Bundler、NetBeansプラグインfor HAML

2010年07月30日

TextMateのBundlerはこちら:

http://github.com/handcrafted/handcrafted-haml-textmate-bundle

NetBeansのプラグインはこちらでダウンロード:

FaqPluginInstall – NetBeans Wiki

ほぼハイライト以外は何の機能もないです。

HAMLでRubyコードを書いても入力補完も、リファレンスも出ませんでした。

Rails: URLをid+slug”の形にカスタマイズ

2010年07月29日

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.

Rails: 必須マークを出力するHelperメソッドを作る

2010年07月27日

一つのHelperメソッドを作って、Modelに必須チェックが入ってるプロパティに対して必須マークの”*”を出力します。

まずapplicaton_helperにmark_requiredのメソッドを作ります。第一引数にはオブジェクト、第二引数はそのクラスのプロパティを渡します。

# application_helper.rb
def mark_required(object, attribute)
  "*" if object.class.validators_on(attribute).map(&:class).include? ActiveModel::Validations::PresenceValidator
end

viewのerbには下記のように@userインスタンス変数と:nameを渡します。もしUserモデルに:nameに対して必須バリデーションが存在すれば必須マークが出力されます。

  <div class="field">
    <%= f.label :name %><%= mark_required(@user, :name) %><br />
    <%= f.text_field :name %>
  </div>

参考リンク:http://railscasts.com/episodes/211-validations-in-rails-3

Rails: カスタム バリデート メソッドを作る

2010年07月25日

http://railscasts.com/episodes/211-validations-in-rails-3で学んだ技です。

Rails 3.0 beta4を利用しています。

カスタムバリデーションメソッドを作成する方法を紹介します。

こんなコードがあるとします。Userモデルのemailに対して妥当性チェックは普通こう書きます。

class User < ActiveRecord::Base
  validates :email,  :format => { :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i }
end

ここの:format => の部分を抽出してemail_validateというバリデーションメソッドを作ります。

方法

libフォルダにemail_format_validator.rbというファイルを新規作成します。

# lib/email_format_validator.rb
class EmailFormatValidator < ActiveModel::EachValidator
  def validate_each(object, attribute, value)
    unless value =~ /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i
      object.errors[attribute] << (options[:message] || "is invalid")
    end
  end
end

そしてUser.rbのソースを下記のように修正します。

#User.rb
class User < ActiveRecord::Base
  validates :email, :email_format => true
end

:email_formatは自動的にEmailFormatValidatorにマッピングします。

Get Adobe Flash playerPlugin by wpburn.com wordpress themes