omniauthのversion上げたらWebサーバ起動時にOmniAuth::VERSION (NameError)

Twitter公式の写真URL取得したいとかで、TwitterGemのバージョンを上げようとしたら、よくわからないことになりました...

Gemfileはこんな感じで

# Gemfile
gem 'twitter', '2.0.0' # ’1.6.0’からUP


アップデート

$ bundle update
Fetching source index for http://rubygems.org/
Bundler could not find compatible versions for gem "faraday":
  In Gemfile:
    twitter (>= 1.9.0) depends on
      faraday (~> 0.7)

    omniauth (~> 0.2.6) depends on
      faraday (0.6.1)

omniauthが古いfradayに依存してるとのこと。



omniauthのReadmeには1.0 has several breaking changes from version 0.x. You can set the dependency to ~> 0.3.2とあるので
GitHub - omniauth/omniauth: OmniAuth is a flexible authentication system utilizing Rack middleware.

こんな感じでGemfile書いて再びbundle updateすると成功。

# Gemfile
gem 'devise'
gem 'omniauth', '~> 0.3.2' # '~> 0.2.6'からUP

そしてWebrickを再起動しようとしたら、OmniAuth::VERSIONって定数がないよ、と。

$ rails s
=> Booting WEBrick
=> Rails 3.1.3 application starting in development on http://0.0.0.0:3000
=> Call with -d to detach
=> Ctrl-C to shutdown server
Exiting
/opt/local/lib/ruby/gems/1.8/gems/devise-1.5.2/lib/devise/omniauth.rb:9: uninitialized constant OmniAuth::VERSION (NameError)

該当のソース見たら、確かに OmniAuth::VERSIONってあるけど1系じゃない場合にエラー上げてる...
いや、OmniauthのReadmeには0.3.2にしてねと書いてあったし...
Deviseには「1.0.0にしろやコラ!」と言われ、omniauthには「1.0.xはちょっとあかんから0.3.2にしといて」と。
はい、すんません。

# /opt/local/lib/ruby/gems/1.8/gems/devise-1.5.2/lib/devise/omniauth.rb
unless OmniAuth::VERSION =~ /^1\./
  raise "You are using an old OmniAuth version, please ensure you have 1.0.0.pr2 version or later installed."
end

試しにこの箇所コメントアウトしてみたら動いた。
でもライブラリ弄ってコミットしたら、オレのマシンでしか動かなくなるし...

悩んだ末、コメントアウトはやめてOmniAuth::VERSIONをenvirment.rbに書くという荒業で様子見しつつちゃんと調べようかな、と。

# envirment.rb
OmniAuth::VERSION='1.0.0'

これで意外にもアプリは何事もなかったかのように動いてるけど、ちゃんと対処したい。
てか、誰かヘルプ...



(解決したので追記)
解消しました。deviseのversionを1.5.2から1.4.9に落とすと「定数ねーよ」エラー出なくなりました。
1.5系は、omniauthの1系じゃないとダメなんすね。
omuniauthの1系が出たタイミングでdeviseも上げよう。

# Gemfile
gem 'devise', '1.4.9'
gem 'omniauth', '~> 0.3.2' # '~> 0.2.6'からUP


以下、自分用メモのbundle list

$ bundle update
Fetching source index for http://rubygems.org/
Enter your password to install the bundled RubyGems to your system: 
Using rake (0.9.2.2) 
Using log4r (1.1.9) 
Using XMLCanonicalizer (1.0.1) 
Using multi_json (1.0.4) 
Using activesupport (3.1.3) 
Using builder (3.0.0) 
Using i18n (0.6.0) 
Using activemodel (3.1.3) 
Using erubis (2.7.0) 
Using rack (1.3.5) 
Using rack-cache (1.1) 
Using rack-mount (0.8.3) 
Using rack-test (0.6.1) 
Using hike (1.2.1) 
Using tilt (1.3.3) 
Using sprockets (2.0.3) 
Using actionpack (3.1.3) 
Using mime-types (1.17.2) 
Using polyglot (0.3.3) 
Using treetop (1.4.10) 
Using mail (2.3.0) 
Using actionmailer (3.1.3) 
Using arel (2.2.1) 
Using tzinfo (0.3.31) 
Using activerecord (3.1.3) 
Using activeresource (3.1.3) 
Using addressable (2.2.6) 
Using bcrypt-ruby (3.0.1) 
Using bundler (1.0.14) 
Using orm_adapter (0.0.5) 
Using warden (1.0.6) 
Using devise (1.4.9) 
Using diff-lcs (1.1.3) 
Using multipart-post (1.1.4) 
Using faraday (0.7.5) 
Using rack-ssl (1.3.2) 
Using json (1.6.2) 
Using rdoc (3.11) 
Using thor (0.14.6) 
Using railties (3.1.3) 
Using jquery-rails (1.0.19) 
Using rails (3.1.3) 
Using kaminari (0.12.4) 
Using systemu (2.4.1) 
Using macaddr (1.5.0) 
Using net-http-digest_auth (1.2) 
Using net-http-persistent (1.9) 
Using nokogiri (1.5.0) 
Using webrobots (0.0.12) 
Using mechanize (2.0.1) 
Using multi_xml (0.4.1) 
Using mysql2 (0.3.10) 
Using net-ldap (0.2.2) 
Using oa-core (0.3.2) 
Using rest-client (1.6.7) 
Using oa-basic (0.3.2) 
Using pyu-ruby-sasl (0.0.3.3) 
Using rubyntlm (0.1.1) 
Using uuid (2.3.4) 
Using oa-enterprise (0.3.2) 
Using oa-more (0.3.2) 
Using oauth (0.4.5) 
Using oauth2 (0.5.1) 
Using oa-oauth (0.3.2) 
Using ruby-openid (2.1.8) 
Using rack-openid (1.3.1) 
Using ruby-openid-apps-discovery (1.2.0) 
Using oa-openid (0.3.2) 
Using omniauth (0.3.2) 
Using ruby-graphviz (0.9.21) 
Using rails-erd (0.4.5) 
Using rspec-core (2.7.1) 
Using rspec-expectations (2.7.0) 
Using rspec-mocks (2.7.0) 
Using rspec (2.7.0) 
Using rspec-rails (2.7.0) 
Using ruby-aaws (0.8.1) 
Using simple_oauth (0.1.5) 
Using sqlite3 (1.3.4) 
Using tlsmail (0.0.1) 
Using twitter-text (1.4.13) 
Using twitter (2.0.0) 
Your bundle is updated! Use `bundle show [gemname]` to see where a bundled gem is installed.
$ 

Twitter風のNoticeメッセージ on Rails3

こういう感じでTwitter風のNoticeメッセージ出したかった。



下記のJQueryのプラグインを利用
Jquery Notification Plugin.


JSはこんな感じでラッピングしとく。
typeもパラメータ渡しするようにしといてもいいかもね。

//public/appllication.js
function show_msg(msg){
  if (msg != '' || msg != null){
    showNotification({
      type: "information",
      message: msg,
      autoClose: true,
      duration: 3
    });
  }
}


コントローラではいつも通りflash[:notice]に文字列埋め込む

# some_controller.rb

def hoge
  flash[:notice] = 'メッセージ'
end


View側ではCSSとプラグイン読み込んで上記で作っておいたshow_msg()に渡す。

# app/views/layouts/application.html.erb

<%= stylesheet_link_tag 'jquery_notification' %>
<%= javascript_include_tag 'jquery_notification_v.1' %>


<% unless flash[:notice].blank? %>
  <script type="text/javascript" charset="utf-8">
    $(function(){
      show_msg('<%= flash[:notice] %>');
    });
  </script>
<% end %>


これで、コントローラ側でflash[:notice]に文字列埋め込んだときだけメッセージがバラっと出てくるようになりましたとさ。

さくらVPSでrails3 + Passenger環境でLD_LIBRARY_PATHがなくて、ってエラー

こんなエラーが出ました。

sqlite3_native.so: undefined symbol: sqlite3_initialize

LD_LIBRARY_PATHを正しく設定してやるといいようで。
下記設定してApache再起動すればエラー出なくなりました。

# /etc/sysconfig/httpd
LD_LIBRARY_PATH=/usr/local/lib
export LD_LIBRARY_PATH

check_box_tagとか

なぜ毎度毎度こんなものを忘れるのだろうか....

なんなの?バカなの?オレ...

書いておこう...


普通に1つ

check_box_tag([カラム名], [値], [初期値])


配列で結果をもらうとき

check_box_tag "hoge[]", "1"
check_box_tag "hoge[]", "2"

# Parameters: {"hoge"=>["1", "2"]}
radio_button_tag(:result, 0, :checked=>'checked') 
radio_button_tag(:result, 1)

f.check_box・check_box_tag、 f.radio_button・radio_button_tagのchecked|DIGITAL SQUADブログ
BRAIN: Rails form check_box_tag

rails3.1.1でLoggerクラスを使ってログ出力を改善するメモ

railsのデフォ設定のログ出力があまりにプアーなのでlog4rでも入れて云々とか考えてたけど標準のLoggerクラスで十分ぽいのでそちらで、ってメモ。


ログ出力サンプル

Started GET "/feed/" for 127.0.0.1 at Sat Nov 12 10:59:42 +0900 2011
[2011-11-12 10:59:42.949642 #12420] [ INFO ] -- :   Processing by UserItemsController#feed as HTML
[2011-11-12 10:59:43.130402 #12420] [DEBUG ] -- :   User Load (0.4ms)  SELECT `users`.* FROM `users` WHERE `users`.`id` = 3 LIMIT 1
[2011-11-12 10:59:43.147146 #12420] [DEBUG ] -- :   User Load (0.4ms)  SELECT `users`.* FROM `users` WHERE `users`.`id` = 3 LIMIT 1
[2011-11-12 10:59:43.155100 #12420] [DEBUG ] -- :   Category Load (0.4ms)  SELECT `categories`.* FROM `categories` WHERE `categories`.`name` = 'Book' LIMIT 1
[2011-11-12 10:59:43.162091 #12420] [DEBUG ] -- :   Category Load (0.3ms)  SELECT `categories`.* FROM `categories` WHERE `categories`.`name` = 'Music' LIMIT 1


config/environment.rb

class Logger
  class Formatter
    def call(severity, time, progname, msg)
      format = "[%s #%d] %5s -- %s: %s\n"
      format % ["#{time.strftime('%Y-%m-%d %H:%M:%S')}.#{'%06d' % time.usec.to_s}",
                  $$, severity, progname, msg2str(msg)]
    end
  end
end


config/environments/[ENVIROMENT].rb

config.logger = Logger.new(config.paths["log"].first)
config.logger.formatter = Logger::Formatter.new
config.logger.datetime_format = "%Y-%m-%d %H:%M:%S"
config.logger.level = Logger::DEBUG
config.colorize_logging = false

[参考]
http://blog.pg1x.com/2011/09/25/rails3%E7%B3%BB%E3%81%AE%E3%83%AD%E3%82%AE%E3%83%B3%E3%82%B0%E8%A8%AD%E5%AE%9A/
资源不存在
あーありがち - 今さらRails3メモ - その3: デバッグというか差し込み口と中身の確認 -

rails コントローラでマルチバイトな文字列カットしたい場合

任意文字数カットしたいってときに、マルチバイト対応してる標準のメソッドが見つからなかったので作ろうかともおもったんだが、
railsのtruncateメソッドパクってくればいいか、ということで下記のメソッドをActiveSupportから取ってきてオレオレライブラリに追加。

なんかやっつけ仕事してる気がするが、そもそもruby1.8.7をいつまでも使ってるのが悪いということですよね。
とりあえず1.9.3までの繋ぎということで...

      def truncate_str(text, *args)
        options = args.extract_options!
        unless args.empty?
          ActiveSupport::Deprecation.warn('truncate takes an option hash instead of separate ' +
            'length and omission arguments', caller)

          options[:length] = args[0] || 30
          options[:omission] = args[1] || "..."
        end
        options.reverse_merge!(:length => 30, :omission => "...")

        if text
          l = options[:length] - options[:omission].mb_chars.length
          chars = text.mb_chars
          (chars.length > options[:length] ? chars[0...l] + options[:omission] : text).to_s
        end
      end

RailsとJQueryでGoogleMapを住所から扱う手軽な方法

GoogleMapをRails3アプリで使いたかった。
昔、どうやってたっけなー、と思って手元のコード参考にかいてもうまく動いてくれなかった。
なんかしばらくのうちにv3とか云々って話になってるので、いい機会なので書きなおしてみた。
Rails:3.1.1


◆JS
プラグインは以下を用いた。
jQuery GoogleMaps プラグイン
GitHub - dreamseeker/jQueryGoogleMaps: Google Maps API v3 を利用するための jQuery Plugin です。


◆View
layouts

<script type="text/javascript" src="http://www.google.com/jsapi">

<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false&key=[key]">

<%= javascript_include_tag 'jquery.GoogleMaps1.01' %>


view/

<script type="text/javascript" charset="utf-8">
$(function(){
  //GMap
  $('#gmap').GoogleMaps({
    lat: <%= @geo['lat'] %>,
    lng: <%= @geo['lng'] %>,
    zoom: 15
  });
});
</script>

<!-- マップ -->
<div id="gmap"></div>


◆Contoroller

controller/

@geo = geocode(@spot_info.address)


common/

 def geocode(address)
   address = URI.encode(address)
   hash = Hash.new
   baseUrl = "http://maps.google.com/maps/api/geocode/json"
   reqUrl = "#{baseUrl}?address=#{address}&sensor=false&language=ja"
   response = Net::HTTP.get_response(URI.parse(reqUrl))
   status = JSON.parse(response.body)
   if status['status'] != "ZERO_RESULTS"
     hash['lat'] = status['results'][0]['geometry']['location']['lat']
     hash['lng'] = status['results'][0]['geometry']['location']['lng']
   else
     hash['lat'] = '35.681382'
     hash['lng'] = '139.766084'
   end
  
   return hash
 end