[Ruby]Passengerのrestart.txtが再起動後削除されないので調べてみた.

Passengerでtmp/restart.txtを作ってやると再起動してrestart.txtが削除されるってどこかに書いてあったと思うけど、再起動後に削除されないので調べてみた.


結果、restart.txtは削除されません.
touchするだけでOK

以下はPassengerのユーザズガイドに書いてました

3.3. Redeploying (restarting the Ruby on Rails application)
3.3. 再配置(Ruby on Railsアプリケーションの再起動)

Deploying a new version of a Ruby on Rails application is as simple as re-uploading the application files, and restarting the application.
Ruby on Railsアプリケーションの新しいバージョンの配置は単純にアプリーケーションファイルの再アップロードとアプリケーションの再起動です.

There are two ways to restart the application:
アプリケーション再起動の方法は二通りある:

1. By restarting Apache.
Apacheを再起動.
2. By creating or modifying the file tmp/restart.txt in the Rails application’s root folder. Phusion Passenger will automatically restart the application.
Railsアプリケーションのルートフォルダ以下にtmp/restart.txtを作成または変更.Phusion Passengerはアプリケーションを自動的に再起動します.

For example, to restart our example MyCook application, we type this in the command line:
例,MyCookアプリケーションを再起動させるためには,以下のコマンドを入力します:

touch /webapps/mycook/tmp/restart.txt

適当に翻訳もしてみた.この再起動の方法2のrestart.txtを作成はまた変更で再起動するとあるけど、再起動後にrestart.txtが削除されるとは書いてない.多分どこかのバージョンで削除しなくなったのだと思う.


それと書かれてないですが、restart.txtファイルの作成後の最初のRailsアプリケーションのアクセス時に再起動するようです.

tmp/restart.txtをSCMにコミットしておいて再起動したいタイミングで書き換えると便利そうだな.

Rails2.3のTLS認証メール送信

今日も凄く躓きました. 開発環境でメールサーバをgmailにしてみようと思ったらできない!

smtp_tls.rbプラグインを使う

いろいろ記事を読むとsmtp_tls.rbなんてプラグインを自作して対応させるって方法が載ってました.

ただ、smtp_tls.rbのプラグインだとRuby1.8.6以前なら動きます.
Ruby1.8.7では以下の部分でこけていました.

    check_auth_args user, secret, authtype if user or secret

これ1.8.7だとcheck_auth_argsってメソッドは引数2個なんですよ.
だから安易に以下の様にして引数を減らすと実際動きました.

    check_auth_args user, secret if user or secret

なんで1.8.7だとNET::SMTPの引数が態々減ってるのか

なんで1.8.7だとNET::SMTPの引数が態々減ってるのか疑問だったんで調べてみた

net/smtp

* SSL/TLS をサポートした(訳注:net/pop は [ruby-dev:34402]OpenSSL::SSL::SSLContext#set_params によれば未だみたい)

SMTPは対応してんじゃん!

Rails2.3での対応

じゃRailsも対応してんじゃね?

予想的中!Railsのコードを呼んでみたら書いてありましたよ!
smtp_settingsにenable_starttls_autoを指定すればいけました!

config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
  :enable_starttls_auto => true,  
  :authentication       => :login,
  :address   => "smtp.gmail.com",
  :port      => "587",
  :domain    => "",
  :user_name => "example@gmail.com",
  :password  => "hogehoge"
}

長かったMacOSFireWallなのかとか、自分の書いたコードがバグなのか、smtp_tls.rbのバグなのかとか散々追いかけまくってたどり着いたorz

Rails2.3のNested Attributesを試してみた.

Nested Attributesを使うと更新がネストしたモデルでもできるとか。

詳しくはhttp://webtama.jp/series/railstips/articles/31を見てください.

では早速、表示させてみる

has_many throughでもできるかが気になったので試してみた

Event <---> EventsUser <---> User

こんな感じで多対多を実現

accepts_nested_attributes_forがミソでこれを指定するとネスト更新が扱えるようになる.

class Event < ActiveRecord::Base
  has_many :users, :through=>:events_users
  accepts_nested_attributes_for :users
end

コントローラにインスタンス変数を作って値をネストさせる

  def index
    @event = Event.new  
    @event.title="EventTitle"
    
    user = User.new
    user.name="Satoruk"
    @event.users << user
    
    respond_to do |format|
      format.html
      format.xml  { render :xml => @event }
    end
  end

ERBで表示

<% form_for(@event) do |f| %>
<%= f.error_messages %>

<% f.fields_for :users  do |user_f| %>
<p>
nsm<%#= user_f.label :name %><br />
<%= user_f.text_field :name %>
</p>
<% end %>

<p>
<%= f.label :title %><br />
<%= f.text_field :title %>
</p>
<p>
<%= f.submit 'Create' %>
</p>
<% end %>


っで実行すると

<form action="/events" class="new_event" id="new_event" method="post"><div style="margin:0;padding:0"><input name="authenticity_token" type="hidden" value="3YNVq51AjbdqB6EVzadnMPiyW5k0irUzPqVebJ3V0Kw=" /></div>

<p>
nsm<br />
<input id="event_users_attributes_0_name" name="event[users_attributes][0][name]" size="30" type="text" value="Satoruk" />
</p>

<p>
<label for="event_title">Title</label><br />
<input id="event_title" name="event[title]" size="30" type="text" value="EventTitle" />
</p>
<p>
<input id="event_submit" name="commit" type="submit" value="Create" />
</p>
</form>

表示できたー、次は登録でも試すか

コンボボックスのポップアップ幅の自動調整

仕事で作ったけど必要なくなったので記録としてエントリーしました.

通常のJComboBoxのポップアップはJComboBoxの幅に合わせて表示されます.
以下のコードは表示幅が狭い場合などポップアップ内のアイテムの文字が切れてしまうのを防ぎます.

        // コンボボックス幅が狭い場合のポップアップ調整
        PopupMenuListener minWidthPopupMenuListener = new PopupMenuListener() {
            private boolean adjusting = false;

            public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
                JComboBox combo = (JComboBox)e.getSource();
                Dimension size = combo.getSize();

                ListCellRenderer renderer = combo.getRenderer();
                JList list = new JList();
                list.setFont(combo.getFont());

                // コンボボックスとレンダラーの結果から最適な幅を計算
                int width = combo.getWidth();
                int itemCount = combo.getItemCount();
                for (int index = 0; index < itemCount; index++) {
                    Object value = combo.getItemAt(index);
                    Component comp = renderer.getListCellRendererComponent(
                        list, value, index, false, false);
                    if (comp != null) {
                        int w = comp.getPreferredSize().width + 5;
                        if (width < w) {
                            width = w;
                        }
                    }
                }

                if (!adjusting) {
                    adjusting = true;
                    combo.setSize(width, size.height);
                    combo.showPopup();
                }
                combo.setSize(size);
                adjusting = false;
            }

            public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {}

            public void popupMenuCanceled(PopupMenuEvent e) {}
        };
        
        combobox.addPopupMenuListener(minWidthPopupMenuListener);


こんなことしなくてもコンボボックスのアイテムが長いの駄目なんだろうけど...

リポジトリ作成

気がつけば、またしばらくエントリしてなかった。
今更ながらGit触ってみました設定だけならsvnより楽でした。

リポジトリの作成

share $ cd sandbox.git/
sandbox.git $ git --bare init
Initialized empty Git repository in /var/www/vhosts/example.com/htdocs/share/sandbox.git/
sandbox.git $ git update-server-info
sandbox.git $ touch git-daemon-export-ok
sandbox.git $ chown -R apache:apache .

Apacheの設定

<VirtualHost 192.168.1.5:80 >
  DocumentRoot /var/www/vhosts/example.com/htdocs
  ServerName example.com
  UseCanonicalName On
  <IfModule mod_dav_fs.c>
    # Location of the WebDAV lock database.
    DAVLockDB /var/lib/dav/lockdb
  </IfModule>
  <Directory /var/www/vhosts/example.com/htdocs >
    Options FollowSymLinks
    Order allow,deny
    Allow from all
  </Directory>
  <Location /share/>
    Options Indexes
    DAV on
    <LimitExcept GET PROPFIND OPTIONS REPORT>
      Require valid-user
      AuthType Basic
      AuthName "catlet password"
      AuthUserFile /var/www/vhosts/example.com/.repo-users
    </LimitExcept>
    Order allow,deny
    Allow from all
  </Location>
  ErrorLog /var/log/httpd/example.com-error_log
  CustomLog /var/log/httpd/example.com-access_log common
</VirtualHost>

日本語メール送信

perl-users.jpのメールの送信 - モダンなPerl入門を手本にメール送信してみたらGMailで文字化けしたので添削。(あとでSVNにコミットするかなしました。)


attributesにcharasetを指定して文字化け対策をしたら直った。

#!/usr/local/bin/perl

use strict;
use warnings;
use utf8;
use Encode;
use Email::MIME;
use Email::MIME::Creator;
use Email::Send;

my $mail = Email::MIME->create(
    header => [
        From    => 'from@example.com',
        To      => 'to@example.co.jp',
        Subject => Encode::encode('MIME-Header-ISO_2022_JP', 'コンニチワ'),
    ],
    attributes => { charset => 'iso-2022-jp' },
    parts => [
        encode('iso-2022-jp', '元気でやってるかー?'),
    ],
    );
                                                                                       
my $sender = Email::Send->new({
                 mailer => 'SMTP',
                 mailer_args => [ Host => 'localhost'],
             });
$sender->send($mail);