RailsはRubyのフレームワークですが、なんだかひとつのアプリケーションのような印象を持っていました。実際には下記のライブラリ群をまとめたものなんですね(1.x系は多少違うかも)。
- ActionMailer
- ActionPack
- ActiveRecord
- ActiveResource
- ActiveSupport
たとえばRailsでアプリケーションを作るほどではないけど、CGIとかでRailsのような書き方をしたいなと思ったら、個別にこれらのライブラリを読み込めばいいのでとても便利です。
今日は↓2つをやってみました。
- メール送信
- DB保存
メール送信 :: ActionMailer
メール送信を行うにはActionMailerを使います。
メール送信のライブラリは青木峰郎さんが作られたTMailが有名ですが、ActionMailerはそのTMailを利用して作られたライブラリです。
ActionMailerを継承してHogeMailerクラスをつくりました。メール作成にはhogeMessageメソッドを使いますが、送信時にdeliver_hogeMessageとなっています。
require 'rubygems' require 'action_mailer' require 'nkf' $KCODE = 'u' class HogeMailer < ActionMailer::Base ActionMailer::Base.smtp_settings = { :address => 'smtp.hogehoge.com', :port => 25, :domain => 'hogehoge.com', :user_name => 'alert@hogehoge.com', :password => 'password', :authentication => :login } @@default_charset = 'iso-2022-jp' @@encode_subject = false def base64(text, charset="iso-2022-jp", convert=true) if convert if charset == "iso-2022-jp" text = NKF.nkf('-j -m0', text) end end text = [text].pack('m').delete("\r\n") "=?#{charset}?B?#{text}?=" end def hogeMessage(toAddress, mySubject, myBody) from base64("hogehoge.com 事務局") + "<noreply @hogehoge.com>" recipients toAddress subject base64(mySubject) body NKF::nkf('-j', myBody) end end taddr = "thisistest@hogehoge.com" # 送信先アドレス ttitle = "タイトル" tbody = "本文" HogeMailer.deliver_hogeMessage(taddr, ttitle, tbody)
日本語でのメール送信は文字コードのことを気にしなければいけないんですね。下のくまくまーさんのサイトを参考にしました。
参考URL
http://wota.jp/ac/?date=20050731
http://d.hatena.ne.jp/GegegeMokeke/20070601
DBへのCRUD :: ActiveRecord
DBへのCRUDはActiveRecordを使います。
同じように継承しているのですが、テーブル名をrequest”s” にしているとしたら、クラス名はRequestにします。これはRailsの規約ですね。単純に保存するだけではつまらないので、保存後にさきのHogeMailerを使ってメールを送ってみます(これもつまらないですね。。。)。
after_save でsending_mailメソッドを呼んでいるのが、その箇所になります。
require 'rubygems' require 'active_record' require 'HogeMailer' class Request < ActiveRecord::Base ActiveRecord::Base.establish_connection( :adapter => 'mysql', :host => 'db.hogehoge.com' :username => 'dbuser', :password => 'password', :database => 'test_db', :encoding => 'utf8' ) after_save :sending_mail def sending_mail title = "#{name}さんからのお知らせ" HogeMailer.deliver_hogeMessage(email, title, body) end end req = Request.new req.name = "お名前" req.email = "hoge@ouboshadesu.com" req.body = "本文" req.save

