ラベル ruby の投稿を表示しています。 すべての投稿を表示
ラベル ruby の投稿を表示しています。 すべての投稿を表示

2015年6月6日土曜日

[Ruby]一桁の日時の値を0埋めしない

0埋めしないようにするには、「-」マイナスつける。
> Time.now.strftime('%Y/%-m/%-d %-H:%-M:%-S') => "2015/6/6 13:9:54"
通常
> Time.now.strftime('%Y/%m/%d %H:%M:%S')=> "2015/06/06 13:10:05"

2014年1月20日月曜日

LazyHighCharts

rubyでグラフが簡単に作れるモジュールを探すとヒットしたのがこのLazyHighCharts。
https://github.com/michelson/lazy_high_charts

Gemfileに下記を追加
gem 'lazy_high_charts
bundle updateの実行
今回は、下記がインスールされました。
lazy_high_charts (1.5.1)


Rails3.2を利用しています。
app/assets/javascripts/application.js に下記のhighchartsの3行を追加
//= require highcharts/highcharts
//= require highcharts/highcharts-more
//= require highcharts/highstock
//= require_tree .

設定はここまで。

ここまで終えたらグラフのソースを書きます。
Controller
  def sell
    @categories = ["apple", "orange", "banana", "strawberry", "melon", "lemon", "peach"]
    @data = [40, 10, 20, 50, 30, 10, 60]
   
    @h = LazyHighCharts::HighChart.new("graph") do |f|
      f.chart(:type => "bar")
      f.title(:text => "Sample bar")
      f.xAxis(:categories => @categories)
      f.series(:name => "Fruits",
               :data => @data)
    end
  end
View
<%= high_chart("sample", @h) %>


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年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月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年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日金曜日

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月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

2012年11月8日木曜日

Rubyで最後の文字取得

最後の文字取得には、いろいろ方法があるとは思いますが、
忘れない内にこんな方法もあるってことを書いておきます。

> str = "ABCDE"
 => "ABCDE"

# 最終文字
> str[-1, 1]
 => "E"

# 最後から3番目の、そこから2文字
> str[-3, 2]
 => "CD"

2012年8月7日火曜日

rubyの小数点計算

小数点の計算と小数点以下N桁の表示にハマったのでメモしておきます。
roundは引数が持てるんですね。

1.9.3p194 :001 > 1/3
 => 0
1.9.3p194 :002 > 1/3.to_f
 => 0.3333333333333333
1.9.3p194 :003 > (1/3.to_f).round
 => 0
1.9.3p194 :004 > (1/3.to_f).round(2)
 => 0.33
1.9.3p194 :005 > 1/4
 => 0
1.9.3p194 :006 > 1.to_f/4
 => 0.25
1.9.3p194 :007 > (1.to_f/4).round
 => 0
1.9.3p194 :008 > (1.to_f/4).round(1)
 => 0.3
1.9.3p194 :009 > (1.to_f/4).round(2)
 => 0.25

2012年6月27日水曜日

railsでMySQLのデータが文字化け

RailsのActiveRecordからMySQLのデータ取得すると日本語が文字化け…。
MySQLのコンソールから見ると、ちゃんと見れる。
mysqldumpをすると文字化け…

default-character-setの指定が必要云々とあったので、
下記ファイルに
sudo /etc/mysql/my.cnf 
これを1行追加して
default-character-set=utf8
MySQL再起動すればOK!
$ sudo /etc/init.d/mysql restart


2012年5月2日水曜日

rvm の更新

今こんなものが入っていて、1.9.3を追加しようかと。
1.9.2だと、Redmine1.4を動かすのにプラグイン周りでエラーが出るのです…。

現状
$ rvm use list

rvm rubies

   jruby-1.6.2 [ amd64 ]
   ree-1.8.7-2011.03 [ x86_64 ]
   ruby-1.8.6-p420 [ x86_64 ]
   ruby-1.8.7-p352 [ x86_64 ]
   ruby-1.9.2-p290 [ x86_64 ]
rvm を最新に更新する 
しばらくやってないからか時間がかかる…
$ rvm get head
アップデートしたrvmの再読み込み
$ rvm reload
RVM reloaded!

インストール可能なRuby一覧
$ rvm list known
# MRI Rubies
[ruby-]1.8.6[-p420]
[ruby-]1.8.7[-p358]
[ruby-]1.8.7-head
[ruby-]1.9.1[-p431]
[ruby-]1.9.2-p180
[ruby-]1.9.2-p290
[ruby-]1.9.2-p318
[ruby-]1.9.2[-p320]
[ruby-]1.9.2-head
[ruby-]1.9.3-preview1
[ruby-]1.9.3-rc1
[ruby-]1.9.3-p0
[ruby-]1.9.3-p125
[ruby-]1.9.3-[p194]
[ruby-]1.9.3-head
ruby-head

1.9.3のインストール
$ rvm install 1.9.3
Installing Ruby from source to: /home/tiffany/.rvm/rubies/ruby-1.9.3-p194, this may take a while depending on your cpu(s)...
"--head"をつけるとリポジトリの最新リビジョン。
付けないとパッチがあたってる最新のものが取れるらしい。

使ってみる
$ rvm use 1.9.3
Using /home/tiffany/.rvm/gems/ruby-1.9.3-p194

1.9.2に切り替えてみる
$ rvm use 1.9.2
ruby-1.9.2-p320 is not installed.
To install do: 'rvm install ruby-1.9.2-p320'
あれ… どもう最新じゃないからインストールせよと…
とりあえず1.9.2もインストール。(こうやって更新するのね。ふむふむ)
$ rvm install ruby-1.9.2-p320

1.9.2に切り替え
$ rvm use 1.9.2
Using /home/tiffany/.rvm/gems/ruby-1.9.2-p320

もともとあった1.9.2には、こんなふうにすれば切り替わる。
$ rvm use ruby-1.9.2-p290
Using /home/tiffany/.rvm/gems/ruby-1.9.2-p290

2012年4月27日金曜日

MD5の作成

picasaにあるようなプライベート設定の認証キーにMD5を使う場合、
RubyからMD5キーを生成してみました。

irbで実行するとこんな感じ。
> require 'digest/md5'
=> true
> Digest::MD5.hexdigest("aa")
=> "4124bc0a9335c27f086f24ba207a4912"
> Digest::MD5.hexdigest("AA")
=> "3b98e2dffc6cb06a89dcb0d5c60a0206"

大文字小文字で違うキーが生成されます。

MD5のreverse用の辞書も存在するので、そこでマッチしない言葉を選びましょう!
http://md5.rednoize.com/

2012年4月20日金曜日

Sinatraをapacheで動かす

sinatraをapacheで動かしてみましょう。
Apacheが入ってることが前提で、passenger のインストールを行います。
先に作成した config.ru が必要になります。

下記を参考にしました!ありがとうございます!
http://d.hatena.ne.jp/foosin/20090619/1245426335

passengerのインストール
2つのモジュールが必要です。
1つ目はあっという間。
$ gem install passenger
Fetching: fastthread-1.0.7.gem (100%)
Building native extensions.  This could take a while...
Fetching: daemon_controller-1.0.0.gem (100%)
Fetching: passenger-3.0.12.gem (100%)
Successfully installed fastthread-1.0.7
Successfully installed daemon_controller-1.0.0
Successfully installed passenger-3.0.12
3 gems installed
Installing ri documentation for fastthread-1.0.7...
Installing ri documentation for daemon_controller-1.0.0...
Installing ri documentation for passenger-3.0.12...
Installing RDoc documentation for fastthread-1.0.7...
Installing RDoc documentation for daemon_controller-1.0.0...
Installing RDoc documentation for passenger-3.0.12...

2つ目はちょっと長いです。
$ passenger-install-apache2-module
Welcome to the Phusion Passenger Apache 2 module installer, v3.0.12.

This installer will guide you through the entire installation process. It
shouldn't take more than 3 minutes in total.

Here's what you can expect from the installation process:

 1. The Apache 2 module will be installed for you.
 2. You'll learn how to configure Apache.
 3. You'll learn how to deploy a Ruby on Rails application.

Don't worry if anything goes wrong. This installer will advise you on how to
solve any problems.

Press Enter to continue, or Ctrl-C to abort.
ここではとりあえずEnter押下。
しばし待つと
 1. The Apache 2 module will be installed for you.
が終わって、
 2. You'll learn how to configure Apache.

の説明が表示されます。

下記3行は環境によって異なりますので、メモしておきます。
あとで必要になります。
Load xxxxx
PassengerRoot xxxxx
PassengerRuby xxxxx

--------------------------------------------
The Apache 2 module was successfully installed.

Please edit your Apache configuration file, and add these lines:

   LoadModule passenger_module /home/tiffany/.rvm/gems/ruby-1.9.2-p290@rails3/gems/passenger-3.0.12/ext/apache2/mod_passenger.so
   PassengerRoot /home/tiffany/.rvm/gems/ruby-1.9.2-p290@rails3/gems/passenger-3.0.12
   PassengerRuby /home/tiffany/.rvm/wrappers/ruby-1.9.2-p290@rails3/ruby

After you restart Apache, you are ready to deploy any number of Ruby on Rails
applications on Apache, without any further Ruby on Rails-specific
configuration!

Press ENTER to continue.
無事インストールされたようなのでEnter押下。
最後に
 3. You'll learn how to deploy a Ruby on Rails application.

で、こういうメッセージが表示されます。
--------------------------------------------
Deploying a Ruby on Rails application: an example

Suppose you have a Rails application in /somewhere. Add a virtual host to your
Apache configuration file and set its DocumentRoot to /somewhere/public:

   <VirtualHost *:80>
      ServerName www.yourhost.com
      # !!! Be sure to point DocumentRoot to 'public'!
      DocumentRoot /somewhere/public   
      <Directory /somewhere/public>
         # This relaxes Apache security settings.
         AllowOverride all
         # MultiViews must be turned off.
         Options -MultiViews
      </Directory>
   </VirtualHost>

And that's it! You may also want to check the Users Guide for security and
optimization tips, troubleshooting and other useful information:

  /home/tiffany/.rvm/gems/ruby-1.9.2-p290@rails3/gems/passenger-3.0.12/doc/Users guide Apache.html

Enjoy Phusion Passenger, a product of Phusion (www.phusion.nl) :-)
http://www.modrails.com/

Phusion Passenger is a trademark of Hongli Lai & Ninh Bui.


Passengerのインストールはこれで終了です。


apacheの設定
環境によって異なると思いますが、、下記のファイルに上記3を参考に設定を行います。
$ sudo vi /etc/apache2/sites-available/xxx
そのファイルに下記を追加します。
上記でメモした3行

   LoadModule passenger_module /home/tiffany/.rvm/gems/ruby-1.9.2-p290@rails3/gems/passenger-3.0.12/ext/apache2/mod_passenger.so
   PassengerRoot /home/tiffany/.rvm/gems/ruby-1.9.2-p290@rails3/gems/passenger-3.0.12
   PassengerRuby /home/tiffany/.rvm/wrappers/ruby-1.9.2-p290@rails3/ruby
モジュールのパス設定
<VirtualHost *:80>
    ServerName www.yourhost.com
    DocumentRoot /home/tiffany/sinatra/public
    <Directory  /home/tiffany/sinatra/public>
        AllowOverride all
        Options -MultiViews
    </Directory>

     ErrorLog /var/log/apache2/error.log
     CustomLog /var/log/apache2/access.log combined
</VirtualHost>

これで、apacheを再起動すればOK!
RACK_ENV=productionでアプリが起動します。
もし、development環境でapache を動かしたい場合は、下記のようにRackEnv development をapacheの設定ファイルに追加してください。
    DocumentRoot /home/tiffany/sinatra/public
    RackEnv development