blog.sowatchasayin

Rails etc.

Showing posts with label Rails. Show all posts
Showing posts with label Rails. Show all posts

Rails cache by memory_store with 1-day expiration

Rails cache has no expiration by default.
So I save the time cached in the cache itself.

カレントディレクトリの*.erbを*.hamlに変換

Hamlいいですねー 楽です。キモ綺麗。
Hamlが動けばZen Codingいらず。

Haml同梱のhtml2hamlってコマンドでerbをhamlにできるのですが、ディレクトリ内一括でやっちゃたいのでちょっと工夫しました。
備忘もかねて投稿。

ruby -e "Dir.glob('*.erb'){|erb|system \"html2haml #{erb} #{erb.sub('erb', 'haml')}\"}" 

ただ、erb.html.erbとかいうファイル名があったらおかしくなっちゃいます。

write meaningful entry

Rails Insideってブログがあります。
その名の通りRuby on Rails情報が載ってるサイトです。
この度、外部の記事提供者を募集し始めるとのこと。
I'm Handing Rails Inside Over To.. You! - Rails Inside


下記、提供記事のガイドラインから引用です。
一般的なブログを書く心得として使えそう。

Some content guidelines:

* News, opinion pieces, event summaries, and link roundups all welcome.
* At least 3 paragraphs.
* At least 200 words. Ideally 220-280 for news, longer as necessary for tutorials or opinion pieces.
* At least one image - which we have the rights to run.. if you use a Creative Commons licensed image, please credit it appropriately.
* Nothing racist/profane/etc, sorry!
* Ensure that the first paragraph is in the 50~80 word range and summarizes (or at least properly introduces) the topic of the post. See existing posts for guidance.
* If something is more suited to RubyFlow or already exists on your own blog, post it on RubyFlow.
* Content should be new/fresh for Rails Inside initially, but you can post it to your own blog too afterwards, of course :-)

最初のパラグラフをサマリにする、ってのは理系論文スタイルですね。
学術論文のメディアとしての洗練され具合は面白いです。査読制度とか。

Rails 2.x.xでException Notifierが動かない時

Rails2.3.5アプリにException Notifierを入れました。

$ script/plugin install http://github.com/rails/exception_notification

諸々設定して起動したのですがこんなエラーが。
/var/lib/gems/1.8/gems/activesupport-2.3.5/lib/active_support/dependencies.rb:105:in `const_missing': uninitialized constant ApplicationController::ExceptionNotifiable (NameError)



調べてみると、Exception NotifierがRails 3に移行している影響みたいです。
Missing ExceptionNotifiable module with exception_notification plugin

なので、3系対応開始前のコミットを使えとのこと。特定のコミットを使うにはscript/pluginじゃないでgit submoduleを使います。
Git clone vs Git submodule
これで一つのリポジトリの中に他のリポジトリが持てます(言い方合ってますかね)。

素直にやってみます。

$ git submodule add git://github.com/rails/exception_notification.git vendor/plugins/exception_notification
$ cd vendor/plugins/exception_notification
$ git checkout -b rails2 e8b603e523c14f145da7b3a1729f5cc06eba2dd1
$ script/server -e production
=> Booting WEBrick
=> Rails 2.3.5 application starting on http://0.0.0.0:3000
** Erubis 2.6.5
=> Call with -d to detach
=> Ctrl-C to shutdown server
[2010-01-29 17:56:33] INFO WEBrick 1.3.1
[2010-01-29 17:56:33] INFO ruby 1.8.7 (2009-06-12) [i486-linux]

動いた♪

redirect_to :back のテスト!!!

でっきたー
@request.envに適当なリファラを入れてあげればOK。
Ruby Nuggets: Testing redirect_to :back shortcut
適当すぎる

Authlogic + factory_girlの罠

Railsの認証プラグインではrestful_authentication迫る人気のauthlogicを使い始めました。
それと同時に!!テストはshoulda、fixtureはやめてfactory_girlを使っています。完全に単なる新しい物好きの挙動です。

それぞれ使い方はgithubのドキュメント見ればわかります。authlogicはサンプルアプリが助かりました。

躓いたところがあるので補足します。

functional testを書いてたら、どうもauthlogicでログインが出来ませぬ。

最初は確かこんな感じ。最後の二つ(password_saltとcrypted_password)は、サンプルアプリのfixtureからとってきました
$ cat test/factories.rb


Factory.define :ユーザさん, :class => User do |f|
f.username "ユーザさん"
f.email "ユーザさん@example.com"
f.password "pasuwado"
f.password_confirmation "pasuwado"
f.password_salt (salt = Authlogic::Random.hex_token)
f.crypted_password {Authlogic::CryptoProviders::Sha512.encrypt("sasasa" + salt)}
end


でも、どうもうまくいかない。Factoryで作ったsaltで暗号化されてないっぽい。何でなの?
調べてみると

it's all good, I am not using fixtures but Factories.
Factory.define :user do |u|
u.login Factory.next :login
u.password "password"
u.password_confirmation "password"
end
now it works fine.

だそうで。いいの?saltとか指定しないで?平気でした。Factoryがよろしく作ってくれました。

なので、これでOK。
$ cat test/factories.rb
Factory.define :ユーザさん, :class => User do |f|
f.username "ユーザさん"
f.email "ユーザさん@example.com"
f.password "pasuwado"
f.password_confirmation "pasuwado"
end


さらに。authlogicはユーザー(例えば。acts_as_authenticなモデル)のインスタンスを生成すると勝手にログインしてくれるので、そこも注意です。

$ cat test/functional/user_sessions_controller_test.rb
require 'test_helper'
class UserSessionsControllerTest < ActionController::TestCase
context "UserSessionsController" do
setup do
activate_authlogic
@ユーザさん = Factory.create(:ユーザさん)
UserSession.find.destroy #ログアウトしておく
end
end

MVC?MCV?

Ruby on Railsの「えせMVC」の弊害
正しくは、MCVじゃないかと思った。

学生の頃、何かしらの哲学者の主張の正確な読解を目指す本を手に取るたび、「それ、今使えんの?」と思ったものでした。
正確な解釈は必要。だけど、今を生きる若者なのでバーリンの解説書でも読むっす。すぐ使えるし。

Railsコードクオリティチェックリスト

直訳タイトルですいません。

Ruby on Rails Code Quality Checklist
via Rails Inside

ぜんぜん守れてないぞ~:-<

メールもrspec on Railsしちゃおう

できるぞ~。

送るメールはファイルを直接読みました。
before do
  raw_email = File.read(RAILS_ROOT + '/どこか/test.eml')
  @mail = TMail::Mail.parse(raw_email)
  @mail.to = "アドレス"
end 

受信はコンソールからやる時と同じ。
to_sでTmailのメールオブジェクトから生メールに戻してあげて。
UserMailer.receive(@mail.to_s)

何を送ったかも~ わかるよ~♪
describe "送ったら" do
  it "送った個数が増えるはず!" do 
  lambda{
    #ここで送る
  }.should change(sent, :count).by(1)
end 
sent.first.bodyで本文見れます。

例によって受け売りです。
RSpec: Testing Mail Delivery (simple)

知らなんだ

render :partialって毎回書くのうっとうしいなー。と思っていたところでした。
基本、パーシャルしかレンダーしないっす。

What's New in Edge Rails: render Stops Being High-Maintenance

2.3からは
render @article

なんとすまーとな。

最新のRailsでrestful_authenticationを使う苦労に苛まれる初秋の一日でした。

2.3.4でrestful_authenticationのspecが通らない。この子たちのせいだった。

Rspecが新しいとダメな所がありました。下記のパッチみたいに直せばOKでした(update for rspec > 1.1.12らしい)。
http://github.com/dchelimsky/restful-authentication/commit/ad92c6cb52500c37ef81e30ac4e79adffc2f4d39

formatted_* routesが無くなった。これで通るっす。
- formatted_user_path(:id => '1', :format => 'xml').should == "/users/1.xml"
- formatted_user_path(:id => '1', :format => 'json').should == "/users/1.json"
+ user_path(:id => '1', :format => 'xml').should == "/users/1.xml"
+ user_path(:id => '1', :format => 'json').should == "/users/1.json"

いきさつ
What's New in Edge Rails: No More Formatted Routes
Add optional :format argument to named routes

XSS怖い、全部マークアップ外す。

XSS怖いですね。
Webのセキュリティ努力のゴールにあるのは「絶望」のみ

ということで遊びで作ってるRailsアプリもちゃんと対策しようと思いました。

で、Safe ERBを入れようとすると。。。
mongrelだと使えない。わざわざWebrickを使うのもメンドウなんです。

探してみたらお便利プラグインありました。
入れただけで、勝手にマークアップをはずします。何もしないでOK。すばらしい。
TechCrunchで挙がっていた例のこいつ
'<script>alert('y0');</script>'

が、こう
'alert('y0');'

なります。

設定すれば一部のカラムだけ除外とかもできるみたいです。リッチなテキストにしたくなったら、そうします。
xss_terminate

ここで見つけました。
Auto-escaping HTML with Rails

AJAXなアクションでflashがついてこない

僕はRailsのflashが好きです。理由はありません。

しかし、こいつ、Ajaxのアクションに対してはうまく動作してくれない。
普通のhttpだとページ遷移すると消えてくれるのですが、どうやらxhrだとそこの片付けをしてくれません。何ということだ…。

なので、下記を参考にがんばって非同期に更新できるようにしました。
Rails Flash with Ajax
flashの部分をpartialに切り出して、毎回page.replace_htmlしてあげる戦略です。

書いてある通りにやろうとしたらダメだった。
ヘルパーにちゃんとpageオブジェクトを渡してあげる。

module ApplicationHelper
~~~~~
def reload_flash(page)
page.replace_html 'flash', :partial => 'layouts/flash'
flash.discard
end
~~~~
end


ちなみにビューのremote_form_forでupdate_pageしようとしたらダメだった。
コントローラを通る前のflashパーシャルをrenderしても、flashに何も入ってないから意味ないし。

traps in a sandbox

Lessons learnt the hard way: Don't use script/console --sandbox on production apps
It also commits implicit commit like ALTER TABLE. just get fucked now.

script/console --sandboxでALTER TABLEとかすると、その前の変更がコミットされちゃいます。くそ!

乗組員。

Debian Lenny + Rails2.3.3 + Passenger2.2.4で、デプロイしたっす。
「とりあえずやってよう」と思いやってみたら、特に何の問題もなく、あっという間に配備できました。
インストール後、
# passenger-install-apache2-module
で対話的に進みます。

参考:
Apache上でRuby on Railsアプリケーションを動かす/Passenger(mod_rails for Apache)の利用

Rails Cheetsheets

Railsで何かするとなると大体googleでサンプルコードを見ることになる。
だって覚えられないんだもん。

ということでチートシート。うーん便利。助かる。
Ruby on Rails > Cheatsheets

site_keyをリポジトリに置いてないが故の。

Restful_AuthenticationのREADMEに「site_keys.rbはリポジトリに置くな」とある。確かに。
で、チェックアウトしたアプリケーションはsite_keyが無いので動かない。

/usr/lib/ruby/gems/1.8/gems/activesupport-2.3.2/lib/active_support/dependencies.rb:443:in `load_missing_constant': uninitialized constant REST_AUTH_SITE_KEY (NameError)

って怒られる。

やっぱり。site_keys.rbはrakeで作れました!
Uninitialized Constant By Password

$ rake auth:gen:site_key

datetime_selectでnilも使いたい。

datetime_selectは、nil値にはデフォルトでなぜか現在時刻が入る。なぜだ!

こうすればnilできた
f.datetime_select :start, :include_blank => true

Nil value on datetime_select?

Author

Fujimura Daisuke
http://fujimuradaisuke.com

Labels