2013年10月25日金曜日

フィーチャーフォンサイトの作成

HTML4.01で、フィーチャーフォン作成時に参考になったサイト

色一覧

テキストに色を付ける時は、fontタグを利用する。
<font color="#333333">文字</font>

2013年10月23日水曜日

コントローラからロケールファイルの読み込み

viewからは、こんなふうで良いけど、Controllerからは I18n を使います。
<%= t("label_login") %>

Controllerでは、
 I18n.t(:notice_saved, :text=>"xxx")


config/locale/ja.yml
ja:
  label_login: "ログイン"
  :notice_saved: "%{text}を保存しました。"



<参考>
http://rails3try.blogspot.jp/2012/01/rails3-i18n.html

2013年10月10日木曜日

Timeの差分

RailsでTimeオブジェクトを引き算した場合に日数を出したい場合

irb(main):072:0> today = Time.now
=> 2013-10-10 16:22:31 +0900
 
irb(main):073:0> beginning_of_month = Time.now.beginning_of_month
=> 2013-10-01 00:00:00 +0900

irb(main):074:0> (today - beginning_of_month).to_i/1.day
=> 9

2013年9月12日木曜日

Rails3で404エラー画面作成

RailsでRoutingErrorが出ると恥ずかしいので、404エラー画面を作ろうと思い、
どう作るんだろう?

参考
http://rochefort.hatenablog.com/entry/2013/02/25/225629

route.rbの一番最後に下記を追加
match '*path', :to => 'application#error_404'

application_controller.rbにerror_404のアクション定義。
def error_404
  error_msg = "<h2>404 Not Found</h2><p>The page you were looking for doesn't exist.</p>"
  render :text => error_msg, :status => 404
end

ここでは、render  :text=>"" にしていますが、
render :template => '/common/error_404' にして、
app/views/common/error_404.html.erb のファイルを作っても良いですね。

意外と簡単でビックリ。

BEFORE







AFTER





2013年8月30日金曜日

LoadError: no such file to load

gemは入っているのに、うまくrequireができない?!

$  gem list --local | grep mysql2
mysql2 (0.3.11)

$ irb
irb(main):001:0> require 'mysql2'
LoadError: no such file to load -- mysql2
        from (irb):1:in `require'
        from (irb):1

どうやら、先に require 'rubygems'  が必要らしい。
irb(main):002:0> require 'rubygems'
=> true
irb(main):003:0> require 'mysql2'
=> true


で、なぜこんなことが必要なんだろう?
いつもはrvmで実行してるけど、
今回は他の人のサーバに設定をすることになり、
すでにモジュールも入った状態。
Ruby One-Click Installer からインストールされた場合の設定??

2013年8月28日水曜日

`autodetect': Could not find a JavaScript runtime

Rails3.2で、railsアプリを作って、コントローラをgenerateしようとしたらエラー。
以前もハマったけど、久々に新しいアプリを作るとハマるので、メモっておく。


エラーログ
/opt/bundle/ruby/2.0.0/gems/execjs-2.0.1/lib/execjs/runtimes.rb:51:in `autodetect': Could not find a JavaScript runtime. See https://github.com/sstephenson/execjs for a list of available runtimes. (ExecJS::RuntimeUnavailable)
        from /opt/bundle/ruby/2.0.0/gems/execjs-2.0.1/lib/execjs.rb:5:in `<module:ExecJS>'
        from /opt/bundle/ruby/2.0.0/gems/execjs-2.0.1/lib/execjs.rb:4:in `<top (required)>'

対処法
Gemfileに下記2行を追加して、bundle updateをすればOK
gem 'therubyracer'
gem 'execjs'

2013年8月26日月曜日

ハッシュキーをシンボルに変換

ハッシュをJSONファイルにして、また戻しての時にハマったのがキー。
JSONファイルにした後に読み込むとシンボルが文字列になってしまうんですね。
他にもいろいろそんなケースが出てきそうなんですが。

Railsの機能にあるHashキーをシンボルに変換するsymbolize_keys
> {"a" => 1, "b" => 2}.symbolize_keys
=> {:a=>1, :b=>2}


JSON.parseでJSONを読み込んでハッシュのキーをシンボルにする場合は、:symbolize_namesのオプションを付与。
>hash = {"a" => 1, "b" => 2}
=> {"a"=>1, "b"=>2}
> json = hash.to_json
=> "{\"a\":1,\"b\":2}"
> JSON.parse(json)
=> {"a"=>1, "b"=>2}
> JSON.parse(json,  {:symbolize_names => true})
=> {:a=>1, :b=>2}

2013年7月9日火曜日

svn dump & load

SVNのダンプとロードについてのメモ。

DUMP
incrementalの有り無しの違いがちょっと分かりづらかったので、
いろいろ聞いてメモっておく。

すべてのダンプをダンプするコマンド
svnadmin dump /opt/svn/xxx > xxx.dump

リビジョン指定の差分ダンプのコマンドにはオプションを付ける。
リビジョン指定+incrementalオプションなし
(100から最新のHEADまで。HEAD以外にも適当なリビジョンの指定も可能)
svnadmin dump /opt/svn/xxx -r 100:HEAD" > diff.dump

リビジョン指定+incrementalオプションあり
svnadmin dump /opt/svn/xxx --incremental -r 100:HEAD" > diff.dump

incrementalありとなしの違いは、incrementalありの場合は、上記例で行くとrev99と100の差分からになる。
incrementalなしだと全ファイルが含まれるため、サイズも大きくなる。
incrementalなしだと、前revがロードされていなくても構築できる(はず)。

LOAD

最初から全部ロードする場合
svnadmin load /opt/svn/yyy < xxx.dump
 
特定のフォルダにロードする場合は、parent-dirのオプションを追加
svnadmin load /opt/svn/yyy --parent-dir /zzz < xxx.dump

2013年6月18日火曜日

mysqlでヘッダ非表示

スクリプトから実行する時に、枠線やヘッダ (カラム名) 不要で値だけ欲しい時、
例えば、データベース一覧のみが欲しい場合のオプションの付け方のメモ。

$ mysql -u [user] -p[password] -N -s -e "show databases;"
db1
db2
db3

-N は、ヘッダなし
-s は枠線なし
-e はコマンド実行

2013年6月4日火曜日

Railsのform_forとパラメータ

form_forを使っている所で、パラメータを渡すのに f.hidden_field を利用した場合、
該当するフィールドがない時に
  WARNING: Can’t mass-assign these protected attributes: id
といったエラーが出ます。

どうやってパラメータを渡せば良いんだろう…?

hidden_fieldではなく、form_forの引数で渡します。


例) project_idを渡したい場合
・新規作成画面へ遷移する時に、コントローラで渡す値を設定
  def new
    ...
    @project_id = xxx
    ...
  end

・new.html.erb の review_record_index_pathのところにパラメータを設定をすると保存ボタン押下時にcreateのところまで渡すことができます。

<%= render(:partial => 'form', :locals => {:path => review_record_index_path(@review_records, :project_id=>@project_id)})  %>


・保存ボタン押下後
  def create
    ...
    puts params[:project_id]
    ...
  end

あまりうまく説明できないけど、こんな感じ…(^^;

2013年5月29日水曜日

passengerのインストール失敗

passengerのインストールの失敗で、スワップ領域が足りなくてエラーになる場合があるそうです。
実際私もハマりました。
この時インストールしたのは、passenger4.0.4でした。
https://groups.google.com/forum/?fromgroups=#!topic/phusion-passenger/V-t5xsHJ4Sw

こちらのサイトにもありますが、同じエラーがでましたね。

rake abortedのエラーがでて、こんなのがずらずら…。

g++ -o agents/PassengerHelperAgent.o  -Iext -Iext/common  -Iext/libev -Iext/libeio -D_REENTRANT -I/usr/local/include -DHAS_TR1_UNORDERED_MAP -DHAVE_ACCEPT4 -DHAS_ALLOCA_H -DHAS_SFENCE -DHAS_LFENCE -Wall -Wextra -Wno-unused-parameter -Wno-parentheses -Wpointer-arith -Wwrite-strings -Wno-long-long -Wno-missing-field-initializers -ggdb -feliminate-unused-debug-symbols -feliminate-unused-debug-types -DPASSENGER_DEBUG -DBOOST_DISABLE_ASSERTS -fcommon -fvisibility=hidden -DVISIBILITY_ATTRIBUTE_SUPPORTED -Wno-attributes -c ext/common/agents/HelperAgent/Main.cpp


サーバーを再起動したらあっさり入りました。

gemの取得先設定/変更

Gem2系から、https://rubygems.org/になりましたが、
社内ネットワークなんかで、httpsがブロックされると悲惨…。

こんなふうに追加ができます。

gem sources --add http://rubygems.org/
gem sources --add http://gems.github.com/
 
削除する時はこんな感じ。
gem sources --remove https://rubygems.org/
 
何が設定されているかは、 gem env コマンドで見てみましょう。 
 
gem sources -l を実行するうと設定されたgemの検索対象部だけが見れます 
 

2013年5月27日月曜日

Passenger 4

ようやく出たと、話題になってるPassenger4。
Ruby2.0と一緒に動かそうとするのだけどなかなか動かず。
先ほどちょうど動きました。
Passenger4.0.3が先週金曜日に出たばかりですね。
http://rubygems.org/gems/passenger
ちょうど金曜日に4.0.2と格闘していて全然ダメだったのですが、4.0.3では結構あっさりと動きました。

  • Ruby2.0.0-p195
  • Rails 3.2.6 (そろそろ3.2.13にしないとな)
  • Passenger 4.0.3

インストールした後、apacheで動かしてみたら
"This application is a Rails 3 application, but it was wrongly detected as a Rails 1 or Rails 2 application. "
こんなエラー…。
そいや、以前もこれ見たな…。
腰を据えて調査してみた所、Apacheの設定が変わったようです。
ここを、こんなふうに変えてあげれば良いのです。
RailsBaseURI /report
 ↓
RackBaseURI /report

Rails3から変更が必要らしいのですが、今までRails3でもRailsBaseURIで動いてたんですよね…。
うーん…

2013年5月24日金曜日

Passengerのインストール

私がよくやらかすエラー。
実行する場所が違うのです…。rails アプリの外でやりましょうってことですね。
エラーが出たら、cd.. でだいたい行けます。

$ passenger-install-apache2-module
/home/xxx/.rvm/rubies/ruby-2.0.0-p0/lib/ruby/site_ruby/2.0.0/rubygems/dependency.rb:296:in `to_specs': Could not find 'passenger' (>= 0) among 102 total gem(s) (Gem::LoadError)
        from /home/xxx/.rvm/rubies/ruby-2.0.0-p0/lib/ruby/site_ruby/2.0.0/rubygems/dependency.rb:307:in `to_spec'
        from /home/xxx/.rvm/rubies/ruby-2.0.0-p0/lib/ruby/site_ruby/2.0.0/rubygems/core_ext/kernel_gem.rb:47:in `gem'
        from /home/xxx/.rvm/gems/ruby-2.0.0-p0@rails3/bin/passenger-install-apache2-module:18:in `<main>'
        from /home/xxx/.rvm/gems/ruby-2.0.0-p0@rails3/bin/ruby_noexec_wrapper:14:in `eval'
        from /home/xxx/.rvm/gems/ruby-2.0.0-p0@rails3/bin/ruby_noexec_wrapper:14:in `<main>'

Ruby2.0

ruby 2.0.0p195 がようやくインストールできた。
出た翌日にrvmから何度もやったけど、うまく行かなくて、ようやく今日無事完了。
入らなかったから、p0で頑張ってたけどね。

以前入れたものから再実行するとごにょごにょ出てきたので、再度rvm get head, rvm reloadから行なってみた。

そしたら、1度アップデートしたせいもあり、すーっと入った。(エラーがは出なくなった!)
しかし、gemが入らない…(どうしても入らない・・・)

$ rvm install 2.0.0
Searching for binary rubies, this might take some time.
Installing requirements for ubuntu, might require sudo password.
ruby-2.0.0-p195 - #configure
ruby-2.0.0-p195 - #download
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100 16.4M  100 16.4M    0     0  5014k      0  0:00:03  0:00:03 --:--:-- 5268k
ruby-2.0.0-p195 - #validate archive
tar: 記録サイズ = 8 ブロック
tar: 記録サイズ = 8 ブロック
ruby-2.0.0-p195 - #extract
ruby-2.0.0-p195 - #validate binary
ruby-2.0.0-p195 - #setup
Saving wrappers to '/home/xxx/.rvm/wrappers/ruby-2.0.0-p195'........
ruby-2.0.0-p195 - #importing default gemsets, this may take time............................


$ ruby -v
ruby 2.0.0p195 (2013-05-14 revision 40734) [x86_64-linux]



昔のバージョン

$ rvm install 2.0.0
Searching for binary rubies, this might take some time.
Installing requirements for ubuntu, might require sudo password.
[sudo] password for xxx:
ヒット http://jp.archive.ubuntu.com lucid Release.gpg
ヒット http://jp.archive.ubuntu.com/ubuntu/ lucid/main Translation-ja
無視 http://jp.archive.ubuntu.com/ubuntu/ lucid/restricted Translation-ja
ヒット http://jp.archive.ubuntu.com/ubuntu/ lucid/universe Translation-ja
ヒット http://security.ubuntu.com lucid-security Release.gpg
ヒット http://ppa.launchpad.net lucid Release.gpg
ヒット http://jp.archive.ubuntu.com/ubuntu/ lucid/multiverse Translation-ja
ヒット http://archive.canonical.com lucid Release.gpg
ヒット http://jp.archive.ubuntu.com lucid-updates Release.gpg
ヒット http://jp.archive.ubuntu.com/ubuntu/ lucid-updates/main Translation-ja
無視 http://jp.archive.ubuntu.com/ubuntu/ lucid-updates/restricted Translation-ja
ヒット http://jp.archive.ubuntu.com/ubuntu/ lucid-updates/universe Translation-ja
無視 http://security.ubuntu.com/ubuntu/ lucid-security/main Translation-ja
無視 http://ppa.launchpad.net/ubuntu-clamav/ppa/ubuntu/ lucid/main Translation-ja
ヒット http://jp.archive.ubuntu.com/ubuntu/ lucid-updates/multiverse Translation-ja
無視 http://archive.canonical.com/ lucid/partner Translation-ja
ヒット http://jp.archive.ubuntu.com lucid Release
ヒット http://jp.archive.ubuntu.com lucid-updates Release
ヒット http://jp.archive.ubuntu.com lucid/main Packages
無視 http://security.ubuntu.com/ubuntu/ lucid-security/restricted Translation-ja
ヒット http://jp.archive.ubuntu.com lucid/restricted Packages
ヒット http://ppa.launchpad.net lucid Release
ヒット http://archive.canonical.com lucid Release
ヒット http://jp.archive.ubuntu.com lucid/main Sources
ヒット http://jp.archive.ubuntu.com lucid/restricted Sources
ヒット http://jp.archive.ubuntu.com lucid/universe Packages
ヒット http://jp.archive.ubuntu.com lucid/universe Sources
無視 http://security.ubuntu.com/ubuntu/ lucid-security/universe Translation-ja
ヒット http://ppa.launchpad.net lucid/main Packages
ヒット http://jp.archive.ubuntu.com lucid/multiverse Packages
ヒット http://archive.canonical.com lucid/partner Packages
ヒット http://jp.archive.ubuntu.com lucid/multiverse Sources
ヒット http://jp.archive.ubuntu.com lucid-updates/main Packages
ヒット http://jp.archive.ubuntu.com lucid-updates/restricted Packages
ヒット http://jp.archive.ubuntu.com lucid-updates/main Sources
無視 http://security.ubuntu.com/ubuntu/ lucid-security/multiverse Translation-ja
ヒット http://jp.archive.ubuntu.com lucid-updates/restricted Sources
ヒット http://jp.archive.ubuntu.com lucid-updates/universe Packages
ヒット http://jp.archive.ubuntu.com lucid-updates/universe Sources
ヒット http://jp.archive.ubuntu.com lucid-updates/multiverse Packages
ヒット http://security.ubuntu.com lucid-security Release
ヒット http://jp.archive.ubuntu.com lucid-updates/multiverse Sources
ヒット http://security.ubuntu.com lucid-security/main Packages
ヒット http://security.ubuntu.com lucid-security/restricted Packages
ヒット http://security.ubuntu.com lucid-security/main Sources
ヒット http://security.ubuntu.com lucid-security/restricted Sources
ヒット http://security.ubuntu.com lucid-security/universe Packages
ヒット http://security.ubuntu.com lucid-security/universe Sources
ヒット http://security.ubuntu.com lucid-security/multiverse Packages
ヒット http://security.ubuntu.com lucid-security/multiverse Sources
パッケージリストを読み込んでいます...
Installing required packages: bash, curl, patch, bzip2, ca-certificates, gawk, g++, gcc, make, libc6-dev, patch, openssl, ca-certificates, libreadline6, libreadline6-dev, curl, zlib1g, zlib1g-dev, libssl-dev, libyaml-dev, libsqlite3-dev, sqlite3, libxml2-dev, libxslt1-dev, autoconf, libc6-dev, libgdbm-dev, libncurses5-dev, automake, libtool, bison, pkg-config, libffi-dev.............................................
ruby-2.0.0-p195 - #configure
ruby-2.0.0-p195 - #download
There is no checksum for 'https://rvm.io/binaries/ubuntu/10.04/x86_64/ruby-2.0.0-p195.tar.bz2?rvm=1.20.9' or 'bin-ruby-2.0.0-p195.tar.bz2', it's not possible to validate it.
This could be because your RVM install's list of versions is out of date. You may want to
update your list of rubies by running 'rvm get stable' and try again.
If that does not resolve the issue and you wish to continue with unverified download
add '--verify-downloads 1' after the command.

Downloading https://rvm.io/binaries/ubuntu/10.04/x86_64/ruby-2.0.0-p195.tar.bz2 failed.

Mounting remote ruby failed, trying to compile.
Installing requirements for ubuntu, might require sudo password.
ヒット http://jp.archive.ubuntu.com lucid Release.gpg
ヒット http://jp.archive.ubuntu.com/ubuntu/ lucid/main Translation-ja
無視 http://jp.archive.ubuntu.com/ubuntu/ lucid/restricted Translation-ja
ヒット http://jp.archive.ubuntu.com/ubuntu/ lucid/universe Translation-ja
ヒット http://archive.canonical.com lucid Release.gpg
ヒット http://ppa.launchpad.net lucid Release.gpg
ヒット http://security.ubuntu.com lucid-security Release.gpg
ヒット http://jp.archive.ubuntu.com/ubuntu/ lucid/multiverse Translation-ja
ヒット http://jp.archive.ubuntu.com lucid-updates Release.gpg
ヒット http://jp.archive.ubuntu.com/ubuntu/ lucid-updates/main Translation-ja
無視 http://jp.archive.ubuntu.com/ubuntu/ lucid-updates/restricted Translation-ja
ヒット http://jp.archive.ubuntu.com/ubuntu/ lucid-updates/universe Translation-ja
無視 http://archive.canonical.com/ lucid/partner Translation-ja
無視 http://ppa.launchpad.net/ubuntu-clamav/ppa/ubuntu/ lucid/main Translation-ja
無視 http://security.ubuntu.com/ubuntu/ lucid-security/main Translation-ja
ヒット http://jp.archive.ubuntu.com/ubuntu/ lucid-updates/multiverse Translation-ja
ヒット http://jp.archive.ubuntu.com lucid Release
ヒット http://jp.archive.ubuntu.com lucid-updates Release
ヒット http://jp.archive.ubuntu.com lucid/main Packages
ヒット http://jp.archive.ubuntu.com lucid/restricted Packages
ヒット http://archive.canonical.com lucid Release
ヒット http://ppa.launchpad.net lucid Release
無視 http://security.ubuntu.com/ubuntu/ lucid-security/restricted Translation-ja
ヒット http://jp.archive.ubuntu.com lucid/main Sources
ヒット http://jp.archive.ubuntu.com lucid/restricted Sources
ヒット http://jp.archive.ubuntu.com lucid/universe Packages
ヒット http://jp.archive.ubuntu.com lucid/universe Sources
ヒット http://archive.canonical.com lucid/partner Packages
ヒット http://jp.archive.ubuntu.com lucid/multiverse Packages
ヒット http://ppa.launchpad.net lucid/main Packages
無視 http://security.ubuntu.com/ubuntu/ lucid-security/universe Translation-ja
ヒット http://jp.archive.ubuntu.com lucid/multiverse Sources
ヒット http://jp.archive.ubuntu.com lucid-updates/main Packages
ヒット http://jp.archive.ubuntu.com lucid-updates/restricted Packages
ヒット http://jp.archive.ubuntu.com lucid-updates/main Sources
ヒット http://jp.archive.ubuntu.com lucid-updates/restricted Sources
無視 http://security.ubuntu.com/ubuntu/ lucid-security/multiverse Translation-ja
ヒット http://jp.archive.ubuntu.com lucid-updates/universe Packages
ヒット http://jp.archive.ubuntu.com lucid-updates/universe Sources
ヒット http://jp.archive.ubuntu.com lucid-updates/multiverse Packages
ヒット http://jp.archive.ubuntu.com lucid-updates/multiverse Sources
ヒット http://security.ubuntu.com lucid-security Release
ヒット http://security.ubuntu.com lucid-security/main Packages
ヒット http://security.ubuntu.com lucid-security/restricted Packages
ヒット http://security.ubuntu.com lucid-security/main Sources
ヒット http://security.ubuntu.com lucid-security/restricted Sources
ヒット http://security.ubuntu.com lucid-security/universe Packages
ヒット http://security.ubuntu.com lucid-security/universe Sources
ヒット http://security.ubuntu.com lucid-security/multiverse Packages
ヒット http://security.ubuntu.com lucid-security/multiverse Sources
パッケージリストを読み込んでいます...
Installing required packages: bash, curl, patch, bzip2, ca-certificates, gawk, g++, gcc, make, libc6-dev, patch, openssl, ca-certificates, libreadline6, libreadline6-dev, curl, zlib1g, zlib1g-dev, libssl-dev, libyaml-dev, libsqlite3-dev, sqlite3, libxml2-dev, libxslt1-dev, autoconf, libc6-dev, libgdbm-dev, libncurses5-dev, automake, libtool, bison, pkg-config, libffi-dev.............................................
Installing Ruby from source to: /home/xxx/.rvm/rubies/ruby-2.0.0-p195, this may take a while depending on your cpu(s)...
ruby-2.0.0-p195 - #downloading ruby-2.0.0-p195, this may take a while depending on your connection...
ruby-2.0.0-p195 - #extracting ruby-2.0.0-p195 to /home/xxx/.rvm/src/ruby-2.0.0-p195
ruby-2.0.0-p195 - #extracted to /home/xxx/.rvm/src/ruby-2.0.0-p195
ruby-2.0.0-p195 - #configuring.....................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................
ruby-2.0.0-p195 - #compiling................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................
ruby-2.0.0-p195 - #installing ...............................................................................................................................................................................................................................................................................................
Retrieving rubygems-2.0.3
######################################################################## 100.0%
Extracting rubygems-2.0.3 ...
Removing old Rubygems files...
Installing rubygems-2.0.3 for ruby-2.0.0-p195...........................................................................................................................................................................................................................................................................................................................................................................................................
Installation of rubygems completed successfully.
Saving wrappers to '/home/xxx/.rvm/wrappers/ruby-2.0.0-p195'........

ruby-2.0.0-p195 - #adjusting #shebangs for (gem irb erb ri rdoc testrb rake).
ruby-2.0.0-p195 - #importing default gemsets, this may take time............................
Install of ruby-2.0.0-p195 - #complete

$ rvm use 2.0.0
Using /home/xxx/.rvm/gems/ruby-2.0.0-p195
$ ruby -v
ruby 2.0.0p195 (2013-05-14 revision 40734) [x86_64-linux]

2013年3月14日木曜日

Rubyによる暗号化/復号化

RubyでAESの暗号化を行う必要があり初めての対応。
今回は復号化する側がJavaらしいので、考慮しつつ…。
Ruby1.9.3を用いて、先のBase64も利用。

スクリプト
require 'openssl'
require 'base64'

def encrypt(data, key, iv)
  cipher = OpenSSL::Cipher.new('aes-128-cbc')
  cipher.encrypt
  cipher.key = key
  cipher.iv = iv
  cipher.update(data) + cipher.final
end

def decrypt(data, key, iv)
  cipher = OpenSSL::Cipher.new('aes-128-cbc')
  cipher.decrypt
  cipher.key = key
  cipher.iv = iv
  cipher.update(data) + cipher.final
end

def main(data)
  key = "1234567890123456"
  iv = "abcdef1234567890"

  # 暗号化
  result = encrypt(data, key, iv)
  base64text = Base64::strict_encode64(result)

  # 復号化
  text = Base64::strict_decode64(base64text)
  dec_data = decrypt(text, key, iv)

  # 確認
  puts "<plain>"
  puts data
  puts "<after decrypt>"
  puts dec_data
  puts "<compare>"
  puts data == dec_data
end

if ARGV.length != 1
  puts "usage: ruby #{__FILE__} data"
  exit 0
end

main(ARGV[0])

注意点
  • cipher.encrypt、cipher.decryptは、インスタンスを作ったら呼んでおく。
  • aes-128-cbc のときは、keyが16bytes、aes-256-cbc のときは、keyを32bytesにする。
    • aes-256-cbc の時にkeyを16bytesにしたままだとこんなエラーが出る。
    • OpenSSL::Cipher::CipherError (key length too short):
  • cipher.final は忘れずに呼んでおく。データは終わりだよという指示。

参考
http://www.ruby-lang.org/ja/old-man/html/OpenSSL_Cipher_Cipher.html
http://blog.matake.jp/archives/openssl_cipher_ruby_jruby
http://techmedia-think.hatenablog.com/entry/20110527/1306499951

2013年3月13日水曜日

RubyのBase64のencode/decode

Ruby1.9.3で、Base64へのencode/decode

> require "base64"
> encode =  Base64.encode64("Hello World!")
=> "SGVsbG8gV29ybGQh\n"
> Base64.decode64(encode)
=> "Hello World!"

2013年1月22日火曜日

プリコミットフックの設定方法

Subversionにて、Rubyのプリコミットフックを作成します。

pre_commit.rb ファイルの作成
例えば、testリポジトリ
$ cd /opt/svn/test/hooks

$ vi pre_commit.rb
 ごにょごにょ記載

適宜権限設定
どう階層にある他のファイルに合わせれば大丈夫。
$ sudo chown www-data:www-data pre_commit.rb
$ sudo chmod 777 pre_commit.rb
pre-commit.tmplからpre-commitの作成
$ cp pre-commit.tmpl pre-commit
$ sudo chown www-data:www-data pre-commit
$ sudo chmod 777 pre-commit
$ vi pre-commit
==
## 日本語を読み込む必要がある場合はこれが必要!
export LANG=ja_JP.UTF-8

REPOS="$1"
TXN="$2"

${REPOS}/hooks/pre_commit.rb "$REPOS" "$TXN"
==
apache再起動

2013年1月11日金曜日

Rails3 ロケールファイルの引数と呼出し方

引数の記述方法と呼出し方法を忘れやすいのでメモ。

ja.yml
label_request: "要望"
label_test: "テストは %{count} 件です"
label_test2: "予定 %{field} 完了数"

xxx.html.erb
# @count = 5 の場合
<%= t('label_test', :count=>@count)%>
<%= t('label_test2', :field=>t('request'))%>

上記のように、引数に別のラベルを入れることも可能。

2013年1月8日火曜日

RubyからSMTPメールを送る方法

ActionMailerもありますが、
とりあえずスクリプトを実行してエラーが出たらメール通知したいので
簡単にできるSMTPメールにしました。

rescueのところで、下記を実装するとエラーが発生したらメール通知してくれます。
rescue => e
 msg = e.backtrace

な感じで書いて、下記の本文にあたるところに #{msg} を書けば、
バックトレースとともに送信される

===
require 'net/smtp'

#SMTP.start でセッションを開く
#第一引数がサーバのアドレスで第二引数がポート番号
#ブロックを使うとセッションの終了を自動的にやってくれる。
Net::SMTP.start( 'your.smtp.server', 25 ) {|smtp|
  #send_mail(テンプレート, 送信元, 送信先)
    smtp.send_mail <<EndOfMail, 'your@mail.address', 'to@some.domain'
From: Your Name <your@mail.address>
To: Dest Address <to@some.domain>
Subject: xxx script error

#{msg}
EndOfMail
}

【参考】
http://d.hatena.ne.jp/gakeno_ueno_horyo/20100917/1284705203