• 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30

Javaはあまり好きではないが、PDF出力ライブラリはiTextが一番だと思っている。GoogleやAdobeのような大手もiTextを利用している事から、その実力は折り紙付きだ。
そもそも、私がJRubyを使い始めたきっかけも、RailsでiTextを使いたかったからだ。

通常、iTextでグラフを生成する場合は、JFreeChartを使うのが一般的だが、今回はiText + Google Chart APIという斬新な組み合わせにチャレンジしてみた。

環境

  • Ubuntu 8.04 64bit
  • JRuby 1.1.4
  • Rails 2.1.2
  • iText 2.1.4


iTextのインストール

下記の3つをダウンロードし、jruby/libディレクトリにコピーする。


PDF出力のメソッド

RailsのControllerにPDF出力用のメソッドを作成。
Google Chart APIのグラフをiTextに埋め込む場合は、URLにパラメータをセットし、それを
document.add(Image::getInstance(URL))
で追加するだけ。
URLに改行コードが入るとエラーになってしまうので、必ずgsubで置換しておくこと。

   1  require 'java'
   2  include_class "java.io.OutputStream"
   3  include_class "java.io.ByteArrayOutputStream"
   4  include_class "java.io.IOException"
   5  include_class "com.lowagie.text.pdf.PdfWriter"
   6  include_class "com.lowagie.text.Document"
   7  include_class "com.lowagie.text.Font"
   8  include_class "com.lowagie.text.pdf.BaseFont"
   9  include_class "com.lowagie.text.Paragraph"
  10  include_class "com.lowagie.text.PageSize"
  11  include_class "com.lowagie.text.Chunk"
  12  include_class "com.lowagie.text.Image"
  13  
  14  class PdfsController < ApplicationController
  15    def pdf
  16      m = ByteArrayOutputStream.new()
  17      document=Document.new() 
  18      writer=PdfWriter.getInstance(document,m)
  19      writer.closeStream = false
  20      document.open()
  21      font = Font.new(BaseFont.createFont("HeiseiMin-W3", "UniJIS-UCS2-H", false),20)
  22      document.add(Paragraph.new("税理士業界におけるSaaSベンダのシェア", font))
  23      
  24      chart = <<-EOS
  25  http://chart.apis.google.com/chart?
  26  chs=460x200
  27  &chd=t:62,12,5,2,19
  28  &cht=p3
  29  &chl=A社|B社|C社|D社|その他
  30      EOS
  31      
  32      document.add(Image::getInstance(chart.gsub!(/\n/, "")))
  33      document.close
  34      send_data String.from_java_bytes(m.toByteArray), :type=> "application/pdf", :dispostion=>"inline"
  35    end
  36  end
sample.pdf ・・・上記のコードで出力したPDF
ご覧の通り、日本語も普通に使える。

まとめ

JFreeChartに比べて、グラフが簡単に作れる。
この組み合わせはなかなかいいなと思った。

posted by Png abikounso on Mon 17 Nov 2008 at 14:00

より快適なRails開発環境を追求するため、今回はソースコード変更時に、自動的にFirefoxをリロードしてくれるスクリプトを作成した。
せっかく作ったので、オープンソースとして公開。
http://github.com/abikounso/auto_reloader/tree/master

環境

  • Ubuntu 8.04
  • JRuby 1.1.4
  • Rails 2.1.2
  • Firefox 3.0.3


リポジトリのコピー

まずは、リポジトリをローカルにコピー

git clone git://github.com/abikounso/auto_reloader.git

auto_reloaderの中には、

mozlab.xpi(Firefoxアドオン)
reload(Rubyスクリプト)

が入っている。

MozLabのインストール

Firefoxにmozlab.xpiをインストールして再起動後、【ツール】>【MozRepl】>【Start】で、telnet接続の準備をしておく。

reloadの配置

reloadをRAILS_ROOT/scriptへコピー。

使い方

下記のコマンドで、監視スタート。

ruby script/reload

監視対象のディレクトリは以下のとおり。

app/controllers
app/helpers
app/models
app/views
public/images
public/javascripts
public/stylesheets

ソースコードを変更して保存すると、ターミナルには

reload /media/disk/workspace/testapp/app/views/hoges/index.html.erb

というメッセージが表示され、Firefoxが自動的にリロードされる。


注意点

  1. Firefoxの公式サイトにあるMozLabだと、Firefox 3.0.3には対応していないので、必ずauto_reloaderの中に入っているMozLabを使うこと。
  2. 先にFirefox側でMozReplをStartさせておかないと、reloadスクリプトがエラーになってしまうので、起動する順番に注意。

まとめ

1日何十〜何百回も
【ソースコード修正】>【アクティブウィンドウをFirefoxに切り替え】>【リロード】
という作業を繰り返していたのが、自動リロードになるだけで超快適。 デュアルディスプレイを使っているなら、なおさら。
監視対象のディレクトリを変更すれば、Rails以外のフレームワークでも使えるので、応用範囲は広い。

posted by Png abikounso on Tue 4 Nov 2008 at 08:48

今回は、RadRailsのデバッグ機能を使ってみた。
結論から言うと、「かなり使える!」


環境

  • Eclipse 3.2.2
  • RadRails 1.0.3


まずは、下準備から。
最初に、RubyForge から、jruby-debug-baseをダウンロードして、インストール。

jruby -S gem install ruby-debug-base-0.10.2-java.gem

さらに、下記の2つもインストール。

jruby -S gem install --ignore-dependencies ruby-debug
jruby -S gem install --ignore-dependencies ruby-debug-ide

インストールが終わったらEclipseを起動し、【Window】→【Preferences】→【Ruby】→【Debugger】→【Use ruby-debug library】にチェックを入れる。 Screenshot-Preferences .png

Railsプロジェクトを起動し、Webサーバをデバッグモードで起動する。 Screenshot-RadRails - Eclipse SDK -3.png

ソースコードにbreakpointを設定し、Railsを実行すると、その箇所で停止する。 Screenshot-Debug - clients_controller.rb - Eclipse SDK .png

変数の確認ができるので、すごく便利。もちろん、ステップ実行もできる。 Screenshot-Debug - clients_controller.rb - Eclipse SDK -1.png

この機能のおかげで、開発がだいぶラクになった。
ただし、重いので、ハイスペックマシンは必須。

posted by Png abikounso on Tue 7 Oct 2008 at 18:47

最近流行っているBDD(振舞駆動開発)というものをやってみたかったので、RSpecとZenTestをインストールしてみた。


環境

  • Ubuntu 8.04
  • JRuby 1.1.4
  • Rails 2.1.1
  • MySQL 5.0.51a
  • RSpec 1.1.8


RSpecをインストール。

gem install rspec

Railsプロジェクトを作成。

jruby -S rails data_conversion -d mysql

プロジェクト作成後、config/database.ymlにhostを書き加えること。これをやらないと、migration時にエラーが発生してしまう。詳しくは、こちらを参照。

RSpecをRailsで使うためのプラグインをインストール。
RSpecやRailsのバージョンによって、インストールするリポジトリが変わるので注意。詳しくはrspec-railsのWikiを参照。

jruby script/plugin install git://github.com/dchelimsky/rspec.git
jruby script/plugin install git://github.com/dchelimsky/rspec-rails.git

RSpecの基本的なファイルを生成。

jruby script/generate rspec

rspec_scaffoldで、通常のscaffold + model、view、controller用のspecファイルを生成。

jruby script/generate rspec_scaffold Client name:string
jruby script/generate rspec_scaffold Journal name:string code:integer client_id:integer

DBとテーブルを作る。

jruby -S rake db:create:all
jruby -S rake db:migrate
jruby -S rake db:test:clone #development用DBのスキーマをtest用DBにコピー

rspec_scaffoldでは、viewのレイアウトファイルは生成されないため、app/views/layouts内に下記の内容のapplication.html.erbを配置する。

   1  <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
   2  
   3  <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="ja" lang="ja">
   4  <head>
   5    <meta http-equiv="content-type" content="text/html;charset=UTF-8" />
   6    <title><%= controller.controller_name %>: <%= controller.action_name %></title>
   7    <%= stylesheet_link_tag 'scaffold' %>
   8  </head>
   9  <body>
  10  
  11  <p style="color: green"><%= flash[:notice] %></p>
  12  
  13  <%= yield  %>
  14  
  15  </body>
  16  </html>

テスト実行。

jruby -S rake spec
rake aborted!

エラーが発生してしまった。なぜ?

どうやら、spec/views/journalsの中の

  • edit.erb_spec.rb
  • index.erb_spec.rb
  • new.erb_spec.rb
  • show.erb_spec.rb
に記述してあるstub_modelが原因のようだ。

   1  stub_model(Journal,
   2    :name => "value for name",
   3    :code => "1",
   4  )

に、:client_id追加してみる。

   1  stub_model(Journal,
   2    :name => "value for name",
   3    :code => "1",
   4    :client_id => "1"
   5  )

再度、テスト実行。

jruby -S rake spec
Finished in 2.017446 seconds

74 examples, 0 failures

今度は通った!
どうやら、rspecでviewのspecファイルを生成すると、stub_modelで外部キーのカラム(ここでは:client_id)が抜けてしまうようだ。

次は、ソースコードを保存した時に、自動的にテストを実行させるための環境構築。

gem install ZenTest
gem install diff-lcs
gem install redgreen #autotest時のコンソール出力に色をつけてくれる

このままautotestを実行するとエラーになってしまうので、下記のメソッドを変更しなければならない。
vendor/plugins/rspec/lib/autotest/rspec.rb

   1  def consolidate_failures(failed)
   2    filters = new_hash_of_arrays
   3    failed.each do |spec, trace|
   4      if trace =~ /\n(\.\/)?(.*spec\.rb):[\d]+:\Z?/
   5        filters[$2] << spec
   6      end
   7    end
   8    return filters
   9  end

を、

   1  def consolidate_failures(failed)
   2    filters = Hash.new { |h,k| h[k] = [] }
   3    failed.each do |spec, trace|
   4      if trace =~ /\n(.*):[\d]+:\Z/
   5        filters[$1] << spec
   6      end
   7    end
   8    return filters
   9  end

に変更。

環境変数に下記の一行を追加。
~/.bashrc

   1  export RSPEC=true

編集後、設定ファイルの再読み込み。

source ~/.bashrc
これを追加しておかないと、
loading autotest/rails
というメッセージがでたまま、止まってしまう。

準備が整ったところで、autotestを実行してみる。

まずは、テスト用サーバの立ち上げ。
立ち上げっぱなしにしておくことで、処理が早くなる。

jruby script/spec_server

新しいコンソール端末を起動して、autotestを実行。

autotest #Railsプロジェクトのルートディレクトリで
Finished in 2.017446 seconds

74 examples, 0 failures

autotest成功!

最後に、テストの結果をポップアップさせるための設定を行う。

ポップアップ表示させるために、Notifyをインストール。

sudo apt-get install libnotify-bin

Railsプロジェクトのルートディレクトリに.autotestというファイルを新規作成し、下記のコードをコピーする。

   1  require 'autotest/redgreen'
   2  
   3  module Autotest::Notify
   4    def self.notify title, msg, img, pri='low', time=3000
   5      `notify-send -i #{img} -u #{pri} -t #{time} '#{msg}'`
   6    end
   7  
   8    Autotest.add_hook :ran_command do |autotest|
   9      results = [autotest.results].flatten.join("\n")
  10      output = results.slice(/(\d+)\s+examples?,\s*(\d+)\s+failures?(,\s*(\d+)\s+pending)?/)
  11      folder = "~/Pictures/rails/"
  12      if output  =~ /[1-9]\d*\sfailures?/
  13        notify "FAIL:", "#{output}", folder+"rails_fail.png", 'critical', 10000
  14      elsif output  =~ /[1-9]\d*\spending?/
  15        notify "PENDING:", "#{output}", folder+"rails_pending.png", 'normal', 10000
  16      else
  17        notify "PASS:", "#{output}", folder+"rails_ok.png"
  18      end
  19    end
  20  end

ポップアップしたときに表示する画像(緑、黄、赤)をこちらのサイトからダウンロードし、~/Pictures/railsフォルダに保存する。

これで、autotest完了時に、以下のポップアップが表示されるようになった。 Screenshot.png

posted by Png abikounso on Sat 27 Sep 2008 at 16:36

scaffold時に自動生成されるテンプレートファイルの場所を調べてみた。


環境

  • JRuby 1.1.4
  • Rails 2.1.1


jruby/lib/ruby/gems/1.8/gems/rails-2.1.1/lib/rails_generator/generators/components/scaffold/templates/

layout.html.erbをXHTML 1.0 Strictに書き換えてみる。

   1  <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
   2  
   3  <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="ja" lang="ja">
   4  <head>
   5    <meta http-equiv="content-type" content="text/html;charset=UTF-8" />
   6    <title><%= controller_class_name %>: <%%= controller.action_name %></title>
   7    <%%= stylesheet_link_tag 'scaffold' %>
   8  </head>
   9  <body>
  10  
  11  <p style="color: green"><%%= flash[:notice] %></p>
  12  
  13  <%%= yield  %>
  14  
  15  </body>
  16  </html>

これで、次回のscaffoldから、上記のレイアウトファイルが出力されるようになる。
ただし、Railsをアップデートすると元に戻ってしまうので注意。

posted by Png abikounso on Fri 26 Sep 2008 at 12:47

Railscastsを参考にしながら、populatorとfakerを使ってみた。


環境

  • JRuby 1.1.4
  • Rails 2.1.1


スキーマは以下の通り。
db/schema.rb

   1  ActiveRecord::Schema.define(:version => 20080924111314) do
   2  
   3  create_table "clients", :force => true do |t|
   4    t.string "name"
   5    t.datetime "created_at"
   6    t.datetime "updated_at"
   7  end
   8  
   9  create_table "journals", :force => true do |t|
  10    t.string "name"
  11    t.integer "code"
  12    t.integer "client_id"
  13    t.datetime "created_at"
  14    t.datetime "updated_at"
  15  end
  16  
  17  end

まずは、必要なものをインストール。

gem install populator
gem install faker

lib/tasks/populate.rakeを作成。

   1  namespace :db do
   2    desc "Erase and fill database" #rake -Tで説明が表示される。
   3    task :populate => :environment do
   4      require 'populator'
   5      require 'faker'
   6  
   7      [Client, Journal].each(&:delete_all)
   8  
   9      Client.populate 20 do |client|
  10        client.name = Faker::Name.name
  11        Journal.populate 5..10 do |journal|
  12          journal.name = Faker::Lorem.words
  13          journal.code = 1000..9999
  14          journal.client_id = client.id
  15        end
  16      end
  17    end
  18  end

ダミーデータの生成。

rake db:populate

こんな感じでダミーデータができあがる。

 index - Mozilla Firefox.png

posted by Png abikounso on Thu 25 Sep 2008 at 13:00
Contents
JRuby + iText + Google Chart APIでPDF出力
Firefoxを自動リロードするRails用スクリプト
Aptana RadRailsで、JRuby on Railsのデバッグ
RSpec+ZenTestで快適Rails開発
Railsのscaffold用テンプレートファイルってどこにあるの?
テスト用のダミーデータを自動生成するRailsプラグイン
Trackbacks
ruby インストール eclipse debug - Google 検索 2/22
jruby ruby-debug - Google 検索 2/22
gem ruby-debug-ide インストール Eclipde - Google 検索 2/22
Table.new JRuby pdf - Google 検索 2/22
rails テストデータ - Google 検索 2/22