<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>cocoa*life &#187; Ruby</title>
	<atom:link href="http://www.cocoalife.net/category/programming/ruby/feed" rel="self" type="application/rss+xml" />
	<link>http://www.cocoalife.net</link>
	<description>Whether we can achieve something entirely depends upon our intensity of faith.</description>
	<lastBuildDate>Sun, 22 May 2011 10:42:49 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>How to create OAuth / xAuth Service Provider in Ruby on Rails with devise</title>
		<link>http://www.cocoalife.net/2011/02/post_866.html</link>
		<comments>http://www.cocoalife.net/2011/02/post_866.html#comments</comments>
		<pubDate>Fri, 04 Feb 2011 03:56:35 +0000</pubDate>
		<dc:creator>milkcocoa</dc:creator>
				<category><![CDATA[Ruby on Rails]]></category>

		<guid isPermaLink="false">http://www.cocoalife.net/?p=866</guid>
		<description><![CDATA[At previous entiry I wrote a sample how to support xAuth in Ruby Application. In this entry, I write how to create the OAuth/xAuth Service Provider in Ruby on Rails project which uses devise plugin for authentication. OAuth support when you use devise plugin Installation First of all, I&#8217;m about to write the way of [...]]]></description>
			<content:encoded><![CDATA[				<p>At previous entiry I wrote a sample how to support xAuth in Ruby Application.</p>
				<p>In this entry, I write how to create the OAuth/xAuth Service Provider in Ruby on Rails project which uses devise plugin for authentication.</p>
				<h2>OAuth support when you use devise plugin</h2>
				<h3>Installation</h3>
				<p>First of all, I&#8217;m about to write the way of supporting OAuth using OAuth plugin.<br />
				<a target="_blank" href="https://github.com/pelle/oauth-plugin">pelle/oauth-plugin &#8211; GitHub</a></p>
				<p>OAuth plugin supports Rails 3 after version 0.4.0.pre1, and add Gemfile the following line.</p>
				<pre class="brush: ruby; title: ; notranslate">gem &quot;oauth-plugin&quot;, &quot;&gt;=0.4.0.pre1&quot;</pre>
<p>The installation tutorials are written in the github plugin page.</p>
<h3>devise plugin support</h3>
<p>In addition, to use OAuth plugin in the project which utilize devise, you need to support two methods &#8220;login_required&#8221; and &#8220;logged_in?&#8221; Devise uses such helper methods as &#8220;authenticate_#{model_name}&#8221; and &#8220;#{model_name}_signed_in?&#8221;, I wrote two helper methods.</p>
<p>[lib/lindoc/oauth_helpers.rb]</p>
<pre class="brush: ruby; title: ; notranslate">module Lindoc
  module OauthHelpers
    def self.included(recipient)
      recipient.extend(ClassMethods)
      recipient.class_eval do
        include InstanceMethods
      end
    end

    module InstanceMethods
      def login_required
        authenticate_user!
      end

      def logged_in?
        user_signed_in?
      end
    end
  end
end</pre>
				<p>At the controllers associated with OAuth, add this helper methods like the this.</p>
				<p>[$RAILS_ROOT/app/oauth_clients_controller.rb]</p>
				<pre class="brush: ruby; title: ; notranslate">class OauthClientsController &lt; ApplicationController
  include Lindoc::OauthHelpers
  ...
end</pre>
				<p>[$RAILS_ROOT/app/oauth_controller.rb]</p>
				<pre class="brush: ruby; title: ; notranslate">require 'oauth/controllers/provider_controller'

class OauthController &lt; ApplicationController
  include OAuth::Controllers::ProviderController
  include Lindoc::OauthHelpers
  ...
end</pre>
				<p>Since I want to use OAuth / xAuth authentication at API of our service, also added :oauth_required filter.</p>
				<p>[app/controllers/api/v1/api_controller.rb]</p>
				<pre class="brush: ruby; title: ; notranslate">class Api::V1::ApiController &lt; ApplicationController
  include Lindoc::OauthHelpers

  before_filter :oauth_required
  ...
end</pre>
				<h3>Rails nested parameters support</h3>
				<p>Client applications often post data in nested parameters like &#8220;foo[bar]=baz&#8221; to Rails application, but OAuth plugin doesn&#8217;t currently support this type of parameters. The reason why OAuth plugin doesn&#8217;t, is that this plugin doesn&#8217;t consider this type when it calculates a signature the way of which is written in the specification of OAuth, and answers a bad/invalid signature. So, you need to add support by overriding the method which helps calculate it.</p>
				<p>This solution is written at Issue page of OAuth plugin.<br />
				<a target="_blank" href="https://github.com/pelle/oauth/issues#issue/8">parameter normalisation issues Nesting parameters causes problems.</a></p>
				<p>[config/initializers/oauth.rb]</p>
				<pre class="brush: ruby; title: ; notranslate">module OAuth
  module Helper
    # see https://github.com/pelle/oauth/issues#issue/8
    def normalize(params)
      params.sort.map do |k, values|
        if values.is_a?(Array)
          # multiple values were provided for a single key
          values.sort.collect do |v|
            [escape(k),escape(v)] * &quot;=&quot;
          end
        elsif values.is_a?(Hash)
          key = k
          values.sort.collect do |k, v|
            [escape(&quot;#{key}[#{k}]&quot;),escape(v)] * &quot;=&quot;
          end
        else
          [escape(k),escape(values)] * &quot;=&quot;
        end
      end * &quot;&amp;&quot;
    end
  end
end]</pre>
				<h2>xAuth support</h2>
				<p>xAuth is the authentication method which is used in twitter to support desktop/mobile applications. If you want to know how to use xAuth in your applications, you should read <a target="_blank" href="http://dev.twitter.com/pages/xauth">this document</a>.<br />
				<a target="_blank" href="http://dev.twitter.com/pages/xauth">Using xAuth | dev.twitter.com</a></p>
				<h3>client application restriction</h3>
				<p>Like twitter, I want to restrict client applications which can use xAuth authentication, and I add column to decide it.</p>
				<p>[db/migrate/xxx_create_oauth_table.rb]</p>
				<pre class="brush: ruby; title: ; notranslate">class CreateOauthTables &lt; ActiveRecord::Migration
  def self.up
    create_table :client_applications do |t|
      ...
      t.boolean :xauth_enabled, :default =&gt; false

      t.timestamps
    end
    ...
  end
end</pre>
				<h3>/oauth/access_token signature verification method change</h3>
				<p>In OAuth 1.0 specification, service provider must verify a signature which consists of both Authentication header and GET or POST parameters called &#8220;Signature Base String&#8221;, and signed by both Consumer Secret and Access Token Secret. This verification step is implemented as filter &#8220;two_legged&#8221; or &#8220;oauth10_request_token&#8221; in OAuth plugin, OAuth::Controllers::ProviderController.</p>
				<p>[oauth-plugin/lib/oauth/controllers/provider_controller.rb]</p>
				<pre class="brush: ruby; title: ; notranslate">module OAuth
  module Controllers

    module ProviderController
      def self.included(controller)
        controller.class_eval do
          ...
          oauthenticate :strategies =&gt; :two_legged, :interactive =&gt; false, :only =&gt; [:request_token]
          oauthenticate :strategies =&gt; :oauth10_request_token, :interactive =&gt; false, :only =&gt; [:access_token]
          ...
</pre>
				<p>The simplified difference of these two methods is to use or not to use request token. You need to change signature verification method of /oauth/access_token when you request Access Token by xAuth, because unlike OAuth clients, xAuth clients don&#8217;t have request token.</p>
				<p>For that reason, to support xAuth, if request has &#8220;x_auth_mode=client_auth&#8221; in POST parametes which indicate client applications want to authenticate by xAuth, &#8220;two_legged&#8221; filter should be applied. I used &#8220;alias_method_chain&#8221; to seperate xAuth and OAuth authentication.</p>
				<p>[config/initializers/oauth.rb]</p>
				<pre class="brush: ruby; title: ; notranslate">module OAuth
  module Controllers
    module ApplicationControllerMethods
      class Authenticator
        def oauth10_request_token_with_xauth
          if params[:x_auth_mode] == 'client_auth'
            # xAuth authentication
            two_legged
          else
            # OAuth authentication
            oauth10_request_token_without_xauth
          end
        end

        alias_method_chain :oauth10_request_token, :xauth
      end
    end
  end
end</pre>
				<h3>/oauth/access_token user verification</h3>
				<p>In /oauth/access_token request, you also verify the user using his username and password. If there is a &#8220;x_auth_mode=client_auth&#8221; POST parameter in request, verify the user and response Access Token.</p>
				<p>[$RAILS_ROOT/app/oauth_controller.rb]</p>
				<pre class="brush: ruby; title: ; notranslate">require 'oauth/controllers/provider_controller'

class OauthController &lt; ApplicationController
  include OAuth::Controllers::ProviderController
  include Lindoc::OauthHelpers
  ....

  private
  def access_token_with_xauth
    # To use custom failure response with devise, you need the following line.
    # see https://github.com/plataformatec/devise/wiki/How-To:-Provide-a-custom-failure-response-with-Warden
    warden.custom_failure!

    if params[:x_auth_mode] == 'client_auth'
      render_unauthorized = Proc.new do
        render :nothing =&gt; true, :status =&gt; 401
      end

      # We support screen name and email to login
      user = User.find_for_database_authentication({ :screen_name_or_email =&gt; params[:x_auth_username] })
      if user &amp;&amp;
        user.valid_password?(params[:x_auth_password]) &amp;&amp;
        current_client_application.xauth_enabled

        @token = AccessToken.where(:user_id.eq =&gt; user,
                                   :client_application_id.eq =&gt; current_client_application,
                                   :invalidated_at.eq =&gt; nil).limit(1).first
        @token = AccessToken.create(:user =&gt; user, :client_application =&gt; current_client_application) if @token.blank?

        if @token
          render :text =&gt; @token.to_query
        else
          render_unauthorized.call
        end
      else
        render_unauthorized.call
      end
    else
      access_token_without_xauth
    end
  end

  alias_method_chain :access_token, :xauth
end</pre>
				<h2>References</h2>
				<ul>
				<li><a target="_blank" href="http://oauth.net/core/1.0/">OAuth Core 1.0</a></li>
				<li><a target="_blank" href="http://d.hatena.ne.jp/yuroyoro/20100506/1273137673">OAuthプロトコルの中身をざっくり解説してみるよ &#8211; ゆろよろ日記</a> (In Japanese)</li>
				<li><a target="_blank" href="https://github.com/oauth/oauth-ruby">oauth/oauth-ruby &#8211; GitHub</a></li>
				<li><a target="_blank" href="https://github.com/pelle/oauth-plugin">pelle/oauth-plugin &#8211; GitHub</a></li>
				<li><a target="_blank" href="https://github.com/pelle/oauth/issues#issue/8">parameter normalisation issues Nesting parameters causes problems.</a></li>
				<li><a target="_blank" href="https://github.com/igaiga/oauth_rails_sample">igaiga/oauth_rails_sample &#8211; GitHub</a></li>
				<li><a target="_blank" href="https://github.com/plataformatec/devise/wiki/How-To:-Provide-a-custom-failure-response-with-Warden">How To: Provide a custom failure response with Warden &#8211; GitHub</a></li>
				</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.cocoalife.net/2011/02/post_866.html/feed</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>xAuth Consumer Sample using Ruby</title>
		<link>http://www.cocoalife.net/2011/01/post_864.html</link>
		<comments>http://www.cocoalife.net/2011/01/post_864.html#comments</comments>
		<pubDate>Fri, 21 Jan 2011 03:57:09 +0000</pubDate>
		<dc:creator>milkcocoa</dc:creator>
				<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://www.cocoalife.net/?p=864</guid>
		<description><![CDATA[I&#8217;m developing OAuth/xAuth Service Provider using OAuth / OAuth-Plugin. pelle/oauth-plugin &#8211; GitHub Since OAuth-Plugin doesn&#8217;t support xAuth, I decided to create a program to support it. I&#8217;ll write an entry about xAuth support, before that, I write this entry about sample of using xAuth in Ruby. You need to install Ruby OAuth Gem. References POST [...]]]></description>
			<content:encoded><![CDATA[				<p>I&#8217;m developing OAuth/xAuth Service Provider using OAuth / OAuth-Plugin.<br />
				<a target="_blank" href="https://github.com/pelle/oauth-plugin">pelle/oauth-plugin &#8211; GitHub</a></p>
				<p>Since OAuth-Plugin doesn&#8217;t support xAuth, I decided to create a program to support it.<br />
				I&#8217;ll write an entry about xAuth support, before that, I write this entry about sample of using xAuth in Ruby.</p>
				<p>You need to install Ruby OAuth Gem.</p>
				<pre class="brush: ruby; title: ; notranslate">require 'oauth'

CONSUMER_KEY = 'Your-Consumer-Key'
CONSUMER_SECRET = 'Your-Consumer-Secret'

def get_access_token
  consumer = OAuth::Consumer.new(CONSUMER_KEY, CONSUMER_SECRET, :site =&gt; 'Your-OAUTH-Provider-URL')
  access_token = consumer.get_access_token(nil, {}, { :x_auth_mode =&gt; 'client_auth', :x_auth_username =&gt; 'Your-User-Name', :x_auth_password =&gt; 'Your-Password' })

  [access_token.token, access_token.secret]
end

def access_api(token, secret)
  consumer = OAuth::Consumer.new(CONSUMER_KEY, CONSUMER_SECRET, :site =&gt; 'Your-OAuth-Provider-URL')
  access_token = OAuth::AccessToken.new(consumer, token, secret)

  access_token.get('Your-API-URL')
end

token, secret = get_access_token
p &quot;token: #{token}&quot;
p &quot;secret: #{secret}&quot;

response = access_api(token, secret)
p response</pre>
				<h2>References</h2>
				<ul>
				<li><a target="_blank" href="http://dev.twitter.com/doc/post/oauth/access_token">POST oauth/access_token | dev.twitter.com</a></li>
				<li><a target="_blank" href="http://d.hatena.ne.jp/lyokato/20100212/1265961914">OAuthでデスクトップアプリがブラウザを経由させたくないときのxAuth &#8211; Codin’ In The Free World</a> (In Japanese)</li>
				<li><a target="_blank" href="http://blog.livedoor.jp/maraigue/archives/1109122.html">Maraigue風。:[Ruby][Twitter] OAuthのアクセストークンを、ブラウザなしで、Twitterのユーザ名およびパスワードのみを用いて取得する(通称：xAuth)ためのRubyのコード</a> (In Japanese)</li>
				</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.cocoalife.net/2011/01/post_864.html/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Find Skype Chat ID with rb-skypemac</title>
		<link>http://www.cocoalife.net/2011/01/post_863.html</link>
		<comments>http://www.cocoalife.net/2011/01/post_863.html#comments</comments>
		<pubDate>Mon, 10 Jan 2011 11:44:28 +0000</pubDate>
		<dc:creator>milkcocoa</dc:creator>
				<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://www.cocoalife.net/?p=863</guid>
		<description><![CDATA[Each Skype chat has an unique chat ID like &#8220;#hogehoge/XXXXXXXXXXXXXXXX&#8221;. This ID has very important role when you handle Skype with another programs/scripts like rb-skypemac (Ruby Gem). rb skypemac There is a very simple method to find IDs with rb-skypemac. After this command, you should select the appropriate ID.]]></description>
			<content:encoded><![CDATA[				<p>Each Skype chat has an unique chat ID like &#8220;#hogehoge/XXXXXXXXXXXXXXXX&#8221;.<br />
				This ID has very important role when you handle Skype with another programs/scripts like <a target="_blank" href="http://rb-skypemac.rubyforge.org/">rb-skypemac (Ruby Gem)</a>.<br />
				<a target="_blank" href="http://rb-skypemac.rubyforge.org/">rb skypemac</a></p>
				<p>There is a very simple method to find IDs with rb-skypemac.</p>
				<pre class="brush: ruby; title: ; notranslate">irb &gt; require 'rb-skypemac'
 =&gt; true
irb &gt; SkypeMac::Skype.send_(:command =&gt; 'SEARCH RECENTCHATS')
 =&gt; &quot;CHATS #hogehoge/XXXXXXXXXXXXXXXX, #piyopiyo/XXXXXXXXXXXXXXXX&quot;</pre>
				<p>After this command, you should select the appropriate ID.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.cocoalife.net/2011/01/post_863.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Installing Chef Server with RVM</title>
		<link>http://www.cocoalife.net/2010/12/post_826.html</link>
		<comments>http://www.cocoalife.net/2010/12/post_826.html#comments</comments>
		<pubDate>Thu, 23 Dec 2010 12:46:36 +0000</pubDate>
		<dc:creator>milkcocoa</dc:creator>
				<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://www.cocoalife.net/?p=826</guid>
		<description><![CDATA[Chef is a systems integration framework, built to bring the benefits of configuration management to your entire infrastructure. The tutorials of install, and basic usage are written here. I want to use it with RVM&#8217;s Ruby on Ubuntu Server 10.10. RVM Installation I use RVM with system wide install, whose instruction is here. RVM: Ruby [...]]]></description>
			<content:encoded><![CDATA[				<p>Chef is a systems integration framework, built to bring the benefits of configuration management to your entire infrastructure.</p>
				<p>The tutorials of install, and basic usage are written <a target="_blank" href="http://wiki.opscode.com/display/chef/Home">here</a>.</p>
				<p>I want to use it with RVM&#8217;s Ruby on Ubuntu Server 10.10.</p>
				<h2>RVM Installation</h2>
				<p>I use RVM with system wide install, whose instruction is <a target="_blank" href="http://rvm.beginrescueend.com/deployment/system-wide/">here</a>.<br />
				<a target="_blank" href="http://rvm.beginrescueend.com/deployment/system-wide/">RVM: Ruby Version Manager &#8211; Installing RVM System Wide</a></p>
				<pre class="brush: bash; title: ; notranslate">chef-server# apt-get install curl git-core
chef-server# bash &lt; &lt;( curl -L http://bit.ly/rvm-install-system-wide )</pre>
				<h2>Ruby 1.9.2 Installation</h2>
				<p>After installed RVM, you need to install Ruby 1.9.2 with RVM.</p>
				<pre class="brush: bash; title: ; notranslate">chef-server# apt-get install build-essential libssl-dev zlib1g-dev libreadline-dev
chef-server# source '/usr/local/lib/rvm'
chef-server# rvm install 1.9.2 -C --with-readline-dir=/usr --with-openssl-dir=/usr --with-zlib-dir=/usr</pre>
				<h2>Bootstrap Chef-Server Installation</h2>
				<p>Now, you are prepared for installing Chef.<br />
				There is a nice tutorial for bootstrap installation of Chef-Server.<br />
				<a target="_blank" href="http://wiki.opscode.com/display/chef/Bootstrap+Chef+RubyGems+Installation">Bootstrap Chef RubyGems Installation &#8211; Chef &#8211; Opscode Open Source Wiki</a></p>
				<h3>Chef Solo Attributes Configuration</h3>
				<pre class="brush: bash; title: ; notranslate">chef-server$ vi ~/chef.json</pre>
<pre class="brush: jscript; title: ; notranslate">{
  &quot;chef&quot;: {
    &quot;server_url&quot;: &quot;http://localhost:4000&quot;
  },
  &quot;run_list&quot;: [ &quot;recipe[chef::bootstrap_server]&quot; ]
}</pre>
				<h3>Temporary PATH configuration</h3>
				<p>Before using Rubygems, you should set PATH configuration temporary, because I want to use chef to set all configurations.</p>
				<pre class="brush: bash; title: ; notranslate">chef-server# source '/usr/local/lib/rvm'
chef-server# rvm use 1.9.2
chef-server# gem install chef</pre>
				<h3>Other Necessary Packages Installation</h3>
				<pre class="brush: bash; title: ; notranslate">chef-server# apt-get install wget ssl-cert
chef-server# gem install chef</pre>
				<h3>Chef Solo Installation</h3>
				<pre class="brush: bash; title: ; notranslate">chef-server# mkdir -p /etc/chef
chef-server# vi /etc/chef/solo.rb</pre>
				<p>The content of &#8220;/etc/chef/solo.rb&#8221; is following.</p>
				<pre class="brush: plain; title: ; notranslate">file_cache_path &quot;/tmp/chef-solo&quot;
cookbook_path &quot;/tmp/chef-solo/cookbooks&quot;</pre>
				<p>You can use `chef-solo` command to install chef-server.</p>
				<pre class="brush: bash; title: ; notranslate">chef-server# chef-solo -c /etc/chef/solo.rb -j ~/chef.json -r http://s3.amazonaws.com/chef-solo/bootstrap-latest.tar.gz</pre>
<h3>chef-client, chef-server, chef-solr, chef-solr-indexer run script PATH configuration</h3>
<p>Having finished installing, you will notice that chef-* fail to start on looking at logs &#8220;/etc/sv/chef-*/logs/main/current&#8221;.<br />
The reason of this failure is that Ruby and Gems PATH are not set correctly, so you should set them like this.</p>
<pre class="brush: bash; title: ; notranslate">chef-server# vi /etc/sv/{chef-client, chef-server, chef-solr, chef-solr-indexer}/run</pre>
				<pre class="brush: diff; title: ; notranslate">- PATH=/usr/local/bin:/usr/local/sbin:/bin:/sbin:/usr/bin:/usr/sbin
---
+ export PATH=/usr/local/bin:/usr/local/sbin:/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/rvm/gems/ruby-1.9.2-p0/bin
+ export GEM_HOME=/usr/local/rvm/gems/ruby-1.9.2-p0
+ export GEM_PATH=/usr/local/rvm/gems/ruby-1.9.2-p0</pre>
				<p>These chef processes are watched by &#8220;runit&#8221;, and after you rewrite them, all processes will start correctly.<br />
				If you want to start/stop/restart manually, use `/etc/init.d/chef-* {start/stop/restart}` command.</p>
				<p>要は、PATH の設定だけちゃんとやっておけば RVM でインストールした Ruby でも Chef はインストールできますよということです。</p>
				<h2>References</h2>
				<ul>
				<li><a target="_blank" href="http://wiki.opscode.com/display/chef/Bootstrap+Chef+RubyGems+Installation">Bootstrap Chef RubyGems Installation &#8211; Chef &#8211; Opscode Open Source Wiki</a></li>
				<li><a target="_blank" href="http://brass.to/blog/try-chef.html">Chefを試してみた &#8211; ひげろぐ</a> (Japanese)</li>
				<li><a href="http://brass.to/blog/1st-chef-solo.html" target="_blank">chef-soloで作業環境構築の自動化 &#8211; ひげろぐ</a> (Japanese)</li>
				<li><a target="_blank" href="http://blog.madoro.org/mn/81">Chefを最速で使いこなすためのいくつかのポイント &#8211; Masatomo Nakano Blog</a> (Japanese)</li>
				<li><a target="_blank" href="http://d.hatena.ne.jp/POCHI_BLACK/searchdiary?word=%2A%5Bchef%5D">[chef] &#8211; pochiのメモ帳</a> (Japanese)</li>
				</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.cocoalife.net/2010/12/post_826.html/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Steak で RESTful API の受け入れテストを書く</title>
		<link>http://www.cocoalife.net/2010/12/post_856.html</link>
		<comments>http://www.cocoalife.net/2010/12/post_856.html#comments</comments>
		<pubDate>Fri, 10 Dec 2010 07:43:43 +0000</pubDate>
		<dc:creator>milkcocoa</dc:creator>
				<category><![CDATA[Ruby on Rails]]></category>

		<guid isPermaLink="false">http://www.cocoalife.net/?p=856</guid>
		<description><![CDATA[Steak は Ruby 製の受け入れテストのためのフレームワークです。 cavalle/steak &#8211; GitHub Github にある説明を読んでいただくとわかると思いますが Steak ではテストは RSpec のように書くことができます。 同様のツールに Cucumber もありますが、Cucumber は英語や日本語で書かなければならないので、自分の中でどうもしっくりしませんでした。 そのため、自分にとっては Steak のようにかけた方がずっと書きやすいです。 ということで、これからは Steak を使って受け入れテストを書いていこうと思っています。 そんな Steak ですが、RESTful API のテストもしたいです。 どうも Steak の裏で動いている Capybara というテストフレームワークは、 visit &#8216;/&#8217; のように GET することはできるのですが、 POST PUT DELETE というような RESTful API をテストする上ではそれだけでは足りません。 以下のような方法で、POST 等のメソッドを呼び出すことが可能なようです。 $RAILS_ROOT/spec/acceptance/support/helper.rb $RAILS_ROOT/spec/acceptance/api/articles_spec.rb @driver.status_code とかでレスポンスのステータスコードが取得できたりします。 ほかの情報はここなどを読むとよいでしょう。 Class: Capybara::Driver::Base 参考文献 [...]]]></description>
			<content:encoded><![CDATA[				<p>Steak は Ruby 製の受け入れテストのためのフレームワークです。<br />
				<a target="_blank" href="https://github.com/cavalle/steak">cavalle/steak &#8211; GitHub</a></p>
				<p>Github にある説明を読んでいただくとわかると思いますが Steak ではテストは RSpec のように書くことができます。<br />
				同様のツールに Cucumber もありますが、Cucumber は英語や日本語で書かなければならないので、自分の中でどうもしっくりしませんでした。<br />
				そのため、自分にとっては Steak のようにかけた方がずっと書きやすいです。<br />
				ということで、これからは Steak を使って受け入れテストを書いていこうと思っています。</p>
				<p>そんな Steak ですが、RESTful API のテストもしたいです。<br />
				どうも Steak の裏で動いている Capybara というテストフレームワークは、 visit &#8216;/&#8217; のように GET することはできるのですが、 POST PUT DELETE というような RESTful API をテストする上ではそれだけでは足りません。</p>
				<p>以下のような方法で、POST 等のメソッドを呼び出すことが可能なようです。</p>
				<p>$RAILS_ROOT/spec/acceptance/support/helper.rb</p>
				<pre class="brush: ruby; title: ; notranslate">module HelperMethods
  def setup_driver
    @driver = Capybara.current_session.driver
  end

  def post(path, params = {})
    @driver.process :post, path, params
  end

  def put(path, params = {})
    @driver.process :put, path, params
  end

  def delete(path, params = {})
    @driver.process :delete, path, params
  end
end</pre>
				<p>$RAILS_ROOT/spec/acceptance/api/articles_spec.rb</p>
				<pre class="brush: ruby; title: ; notranslate">require File.dirname(__FILE__) + '/../acceptance_helper'

feature &quot;Articles&quot; do
  background do
    setup_driver
  end

  scenario 'update article' do
    params = { :article =&gt; {} }
    params[:article][:title] = 'foo'
    put('/api/articles/1.json', params)
  end
end</pre>
				<p>@driver.status_code とかでレスポンスのステータスコードが取得できたりします。<br />
				ほかの情報は<a target="_blank" href="http://rubydoc.info/github/jnicklas/capybara/master/Capybara/Driver/Base">ここ</a>などを読むとよいでしょう。<br />
				<a target="_blank" href="http://rubydoc.info/github/jnicklas/capybara/master/Capybara/Driver/Base">Class: Capybara::Driver::Base</a></p>
				<h2>参考文献</h2>
				<ul>
				<li><a target="_blank" href="https://github.com/cavalle/steak">cavalle/steak &#8211; GitHub</a></li>
				<li><a target="_blank" href="https://github.com/jnicklas/capybara">jnicklas/capybara &#8211; GitHub</a></li>
				<li><a target="_blank" href="http://blog.ardes.com/2010/4/28/capybara-and-rack-test-sessions-and-http-methods">Capybara attack: rack-test, lost sessions and http request methods</a></li>
				<li><a target="_blank" href="http://rubydoc.info/github/jnicklas/capybara/master/Capybara/Driver/Base">Class: Capybara::Driver::Base</a></li>
				</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.cocoalife.net/2010/12/post_856.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>JRuby で ActiveRecord 3 をちょこっと試す</title>
		<link>http://www.cocoalife.net/2010/12/post_861.html</link>
		<comments>http://www.cocoalife.net/2010/12/post_861.html#comments</comments>
		<pubDate>Tue, 07 Dec 2010 09:28:08 +0000</pubDate>
		<dc:creator>milkcocoa</dc:creator>
				<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://www.cocoalife.net/?p=861</guid>
		<description><![CDATA[JRuby で ActiveRecord を試してみたいと思いました。 JRuby は RVM で 1.5.6 がインストールされています。 こんな感じで .rvmrc を使用して JRuby 環境になっているものとします。 まずは ActiveRecord のインストール。 MySQL を使いたいので、普通の Ruby っぽく とやってみましたが、ダメでした。 こういうのを使う必要があるらしいです。 establish_connection のやり方も若干違います。 あとは同じみたいです。 参考文献 Using ActiveRecord and JDBC with JRuby Using ActiveRecord and JDBC with JRuby – Part 2]]></description>
			<content:encoded><![CDATA[				<p>JRuby で ActiveRecord を試してみたいと思いました。<br />
				JRuby は RVM で 1.5.6 がインストールされています。</p>
				<pre class="brush: bash; title: ; notranslate">$ echo &quot;rvm jruby&quot; &gt;&gt; .rvmrc</pre>
<p>こんな感じで .rvmrc を使用して JRuby 環境になっているものとします。</p>
<p>まずは ActiveRecord のインストール。</p>
<pre class="brush: bash; title: ; notranslate">$ gem install activerecord
Successfully installed activesupport-3.0.3
Successfully installed builder-2.1.2
Successfully installed i18n-0.5.0
Successfully installed activemodel-3.0.3
Successfully installed arel-2.0.6
Successfully installed tzinfo-0.3.23
Successfully installed activerecord-3.0.3
7 gems installed (...)</pre>
				<p>MySQL を使いたいので、普通の Ruby っぽく</p>
				<pre class="brush: bash; title: ; notranslate">$ gem install mysql</pre>
<p>とやってみましたが、ダメでした。</p>
<pre class="brush: bash; title: ; notranslate">$ gem install activerecord-jdbcmysql-adapter
Successfully installed activerecord-jdbc-adapter-1.0.3-java
Successfully installed jdbc-mysql-5.0.4
Successfully installed activerecord-jdbcmysql-adapter-1.0.3-java
3 gems installed (...)</pre>
				<p>こういうのを使う必要があるらしいです。<br />
				establish_connection のやり方も若干違います。</p>
				<pre class="brush: ruby; title: ; notranslate">require 'rubygems'
require 'active_record'

ActiveRecord::Base.establish_connection(
  :adapter =&gt; 'jdbcmysql',
  :host =&gt; 'localhost',
  :username =&gt; 'root',
  :password =&gt; '',
  :database =&gt; 'piyopiyo_development',
  :pool =&gt; 5
)</pre>
				<p>あとは同じみたいです。</p>
				<h2>参考文献</h2>
				<ul>
				<li><a target="_blank" href="http://rubylearning.com/blog/2008/07/28/using-activerecord-and-jdbc-with-jruby/">Using ActiveRecord and JDBC with JRuby</a></li>
				<li><a target="_blank" href="http://rubylearning.com/blog/2008/07/30/using-activerecord-and-jdbc-with-jruby-part-2/">Using ActiveRecord and JDBC with JRuby – Part 2</a></li>
				</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.cocoalife.net/2010/12/post_861.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Rails 3 で Paperclip Processor を使用する</title>
		<link>http://www.cocoalife.net/2010/10/post_854.html</link>
		<comments>http://www.cocoalife.net/2010/10/post_854.html#comments</comments>
		<pubDate>Wed, 20 Oct 2010 10:36:15 +0000</pubDate>
		<dc:creator>milkcocoa</dc:creator>
				<category><![CDATA[Ruby on Rails]]></category>

		<guid isPermaLink="false">http://www.cocoalife.net/?p=854</guid>
		<description><![CDATA[Paperclip は高機能なファイル添付のための Rails プラグインです。 thoughtbot&#8217;s paperclip at master &#8211; GitHub 単純にアップロードが行えるだけではなく、アップロードされたファイルを処理する Processor という仕組みがあります。 Railscasts でも紹介されています。 Railscasts &#8211; Cropping Images この Processor を作成するには Paperclip::Processor というのを継承して、 $RAILS_ROOT/lib/paperclip_processors/hoge.rb みたいな場所に置きます。 この Processor の仕組みが今回必要だったので、 Rails 3 で動かしてみたところ、動いている気配がない。 そこで Processor not loading at first try with Rails3 &#8211; Paperclip Plugin というのを参考にして、以下のコードを書いてみたところ無事に読み込まれました。 これを config/initializers/paperclip.rb として置いておきました。 より詳しい Processor の作成方法については以下の blog に非常に詳しく書かれています。 動画をアップロードされたら ffmpeg [...]]]></description>
			<content:encoded><![CDATA[				<p>Paperclip は高機能なファイル添付のための Rails プラグインです。</p>
				<p><a target="_blank" href="http://github.com/thoughtbot/paperclip">thoughtbot&#8217;s paperclip at master &#8211; GitHub</a></p>
				<p>単純にアップロードが行えるだけではなく、アップロードされたファイルを処理する Processor という仕組みがあります。<br />
				Railscasts でも紹介されています。<br />
				<a href="http://railscasts.com/episodes/182-cropping-images">Railscasts &#8211; Cropping Images</a></p>
				<p>この Processor を作成するには Paperclip::Processor というのを継承して、 $RAILS_ROOT/lib/paperclip_processors/hoge.rb みたいな場所に置きます。</p>
				<p>この Processor の仕組みが今回必要だったので、 Rails 3 で動かしてみたところ、動いている気配がない。<br />
				そこで <a target="_blank" href="http://groups.google.com/group/paperclip-plugin/browse_thread/thread/0882c396ebf7edbf/0221616d4da214e7?lnk=raot">Processor not loading at first try with Rails3 &#8211; Paperclip Plugin</a> というのを参考にして、以下のコードを書いてみたところ無事に読み込まれました。</p>
				<pre class="brush: ruby; title: ; notranslate">Hoge::Application.configure do
  config.after_initialize do
    Dir.glob(File.join(File.expand_path(Rails.root), &quot;lib&quot;, &quot;paperclip_processors&quot;, &quot;*.rb&quot;)).each do |processor|
      require processor
    end
  end
end</pre>
				<p>これを config/initializers/paperclip.rb として置いておきました。</p>
				<p>より詳しい Processor の作成方法については以下の blog に非常に詳しく書かれています。<br />
				動画をアップロードされたら ffmpeg でサムネイルを作成する方法について書かれていて、非常に参考になります。<br />
				<a target="_blank" href="http://thewebfellas.com/blog/2009/2/22/video-thumbnails-with-ffmpeg-and-paperclip">Video thumbnails with FFmpeg and Paperclip – Ruby on Rails, JRuby, AWS, EC2, Exalead</a></p>
				<p>注意点としては、 has_attached_file にちゃんと :styles プロパティを設定しておくこと。<br />
				これをしないと :processors => [ :hoge ] と書いても、その Processor は呼ばれません。</p>
				<h2>参考文献</h2>
				<ul>
				<li><a target="_blank" href="http://groups.google.com/group/paperclip-plugin/browse_thread/thread/0882c396ebf7edbf/0221616d4da214e7?lnk=raot">Processor not loading at first try with Rails3 &#8211; Paperclip Plugin</a></li>
				<li><a href="http://railscasts.com/episodes/182-cropping-images">Railscasts &#8211; Cropping Images</a></li>
				<li><a target="_blank" href="http://thewebfellas.com/blog/2009/2/22/video-thumbnails-with-ffmpeg-and-paperclip">Video thumbnails with FFmpeg and Paperclip – Ruby on Rails, JRuby, AWS, EC2, Exalead</a></li>
				</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.cocoalife.net/2010/10/post_854.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Rails 3 + Haml で production 環境下でもインデントする</title>
		<link>http://www.cocoalife.net/2010/10/post_853.html</link>
		<comments>http://www.cocoalife.net/2010/10/post_853.html#comments</comments>
		<pubDate>Wed, 20 Oct 2010 09:32:48 +0000</pubDate>
		<dc:creator>milkcocoa</dc:creator>
				<category><![CDATA[Ruby on Rails]]></category>

		<guid isPermaLink="false">http://www.cocoalife.net/?p=853</guid>
		<description><![CDATA[Haml をしようするときれいにインデントがされるから好きなんですが、Rails の production 環境下ではインデントがされません。 Haml2.2からはRailsのproductionでインデントが無いと少数派に呼びかけている &#8211; komagata [p0t] 速度が問題になるまではインデントしたいので、上記 komagata さんが書かれているように設定したものの、 Rails 3 では上手く動きませんでした。 config.after_initialize でくくらないといけないみたいです。 これを config/initializers/haml.rb に置きました。 1 config/application.rb や config/environments/production.rb の中でもいいですね（たぶん）。 Hoge は適当なアプリケーション名に置き換えること。]]></description>
			<content:encoded><![CDATA[				<p><a target="_blank" href="http://haml-lang.com/">Haml</a> をしようするときれいにインデントがされるから好きなんですが、Rails の production 環境下ではインデントがされません。</p>
				<p><a target="_blank" href="http://docs.komagata.org/4501">Haml2.2からはRailsのproductionでインデントが無いと少数派に呼びかけている &#8211; komagata [p0t]</a></p>
				<p>速度が問題になるまではインデントしたいので、上記 komagata さんが書かれているように設定したものの、 Rails 3 では上手く動きませんでした。</p>
				<p>config.after_initialize でくくらないといけないみたいです。</p>
				<pre class="brush: ruby; title: ; notranslate">Hoge::Application.configure do
  config.after_initialize do
    Haml::Template::options[:ugly] = false
  end
end</pre>
				<p>これを config/initializers/haml.rb に置きました。 <sup><a href="http://www.cocoalife.net/2010/10/post_853.html#footnote_0_853" id="identifier_0_853" class="footnote-link footnote-identifier-link" title="Hoge は適当なアプリケーション名に置き換えること。">1</a></sup><br />
				config/application.rb や config/environments/production.rb の中でもいいですね（たぶん）。</p>
				<ol class="footnotes"><li id="footnote_0_853" class="footnote">Hoge は適当なアプリケーション名に置き換えること。</li></ol>
]]></content:encoded>
			<wfw:commentRss>http://www.cocoalife.net/2010/10/post_853.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Ruby 1.9.2 で aws-s3 を使用できなかった問題の解決策</title>
		<link>http://www.cocoalife.net/2010/10/post_852.html</link>
		<comments>http://www.cocoalife.net/2010/10/post_852.html#comments</comments>
		<pubDate>Tue, 19 Oct 2010 07:44:40 +0000</pubDate>
		<dc:creator>milkcocoa</dc:creator>
				<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://www.cocoalife.net/?p=852</guid>
		<description><![CDATA[Ruby 1.9.2 が使いたいなぁと思って、いろいろとやっています。 Amazon S3 を使用したいと思って、手持ちの Mac に定番の aws-s3 をインストールして irb で試してみようとするとエラーが出て使用できませんでした。 marcel&#8217;s aws-s3 at master &#8211; GitHub ところが Linux ではちゃんと動きます。 特にバイナリをビルドしている様子もないので、こちらの環境が悪いと判断しました。 環境 Ruby 1.9.2 on RVM エラー内容 irb > require 'aws/s3' SyntaxError: /Users/piyo/.rvm/gems/ruby-1.9.2-p0/gems/aws-s3-0.6.2/lib/aws/s3/extensions.rb:84: invalid multibyte escape: /[ \x80-\xFF]/ from :29:in `require' from :29:in `require' from /Users/piyo/.rvm/gems/ruby-1.9.2-p0/gems/aws-s3-0.6.2/lib/aws/s3.rb:11:in `' from :33:in `require' from :33:in `rescue in [...]]]></description>
			<content:encoded><![CDATA[				<p>Ruby 1.9.2 が使いたいなぁと思って、いろいろとやっています。<br />
				Amazon S3 を使用したいと思って、手持ちの Mac に定番の aws-s3 をインストールして irb で試してみようとするとエラーが出て使用できませんでした。</p>
				<p><a target="_blank" href="http://github.com/marcel/aws-s3">marcel&#8217;s aws-s3 at master &#8211; GitHub</a></p>
				<p>ところが Linux ではちゃんと動きます。<br />
				特にバイナリをビルドしている様子もないので、こちらの環境が悪いと判断しました。</p>
				<h2>環境</h2>
				<ul>
				<li>Ruby 1.9.2 on RVM</li>
				</ul>
				<h2>エラー内容</h2>
				<pre>irb > require 'aws/s3'
SyntaxError: /Users/piyo/.rvm/gems/ruby-1.9.2-p0/gems/aws-s3-0.6.2/lib/aws/s3/extensions.rb:84: invalid multibyte escape: /[
\x80-\xFF]/
        from <internal:lib/rubygems/custom_require>:29:in `require'
        from <internal:lib/rubygems/custom_require>:29:in `require'
        from /Users/piyo/.rvm/gems/ruby-1.9.2-p0/gems/aws-s3-0.6.2/lib/aws/s3.rb:11:in `<top (required)>'
        from <internal:lib/rubygems/custom_require>:33:in `require'
        from <internal:lib/rubygems/custom_require>:33:in `rescue in require'
        from <internal:lib/rubygems/custom_require>:29:in `require'
        from (irb):1
        from /Users/piyo/.rvm/rubies/ruby-1.9.2-p0/bin/irb:17:in `<main>'</pre>
				<h2>解決策</h2>
				<p>.zshrc に RUBYOPT=-Ku が設定されていたので、その設定を外しました。</p>
]]></content:encoded>
			<wfw:commentRss>http://www.cocoalife.net/2010/10/post_852.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Lokka を nginx + Unicorn で動かす</title>
		<link>http://www.cocoalife.net/2010/10/post_851.html</link>
		<comments>http://www.cocoalife.net/2010/10/post_851.html#comments</comments>
		<pubDate>Fri, 15 Oct 2010 05:44:33 +0000</pubDate>
		<dc:creator>milkcocoa</dc:creator>
				<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://www.cocoalife.net/?p=851</guid>
		<description><![CDATA[Lokka は komagata さんが開発されている、Ruby で書かれた CMS です（旧名 Pyhä）。 以前書いたエントリのように、Lokka も nginx と Unicorn で動かしたいと思います。 cocoa*life &#8211; Redmine を nginx + Unicorn で動かしてみる Lokka は Sinatra ベースなので Sinatra で動かすようにすればいいだけのようです。 Unicorn の設定 Lokka のディレクトリに unicorn.rb というファイルを作成しました。 unicorn.rb は前回の使用したものをほぼそのまま使用しました。 Unicorn を起動する nginx の設定 nginx の設定は以下のようにしました。 nginx を再起動する。 参考文献 UnicornでSinatraアプリをデプロイしてみた &#8211; 射撃しつつ前転]]></description>
			<content:encoded><![CDATA[				<p><a target="_blank" href="">Lokka</a> は komagata さんが開発されている、Ruby で書かれた CMS です（旧名 Pyhä）。</p>
				<p><a target="_blank" href="http://www.cocoalife.net/2010/10/post_77.html<br />
				">以前書いたエントリ</a>のように、Lokka も nginx と Unicorn で動かしたいと思います。<br />
				<a target="_blank" href="http://www.cocoalife.net/2010/10/post_77.html<br />
				">cocoa*life &#8211; Redmine を nginx + Unicorn で動かしてみる</a></p>
				<p>Lokka は Sinatra ベースなので Sinatra で動かすようにすればいいだけのようです。</p>
				<h2>Unicorn の設定</h2>
				<p>Lokka のディレクトリに unicorn.rb というファイルを作成しました。<br />
				unicorn.rb は前回の使用したものをほぼそのまま使用しました。</p>
				<pre class="brush: ruby; title: ; notranslate"># ワーカーの数
worker_processes 2

# ソケット
listen '/tmp/unicorn-lokka.sock'

# ログ
stderr_path 'tmp/log/unicorn.log'
stdout_path 'tmp/log/unicorn.log'

# ダウンタイムなくす
preload_app true

before_fork do |server, worker|
  old_pid = &quot;#{ server.config[:pid] }.oldbin&quot;
  unless old_pid == server.pid
    begin
      # SIGTTOU だと worker_processes が多いときおかしい気がする
      Process.kill :QUIT, File.read(old_pid).to_i
    rescue Errno::ENOENT, Errno::ESRCH
    end
  end
end</pre>
				<p>Unicorn を起動する</p>
				<pre class="brush: bash; title: ; notranslate">unicorn -c unicorn.rb -D</pre>
<h2>nginx の設定</h2>
<p>nginx の設定は以下のようにしました。</p>
<pre class="brush: plain; title: ; notranslate">upstream unicorn-lokka {
         server unix:/tmp/unicorn-lokka.sock;
}

server {
        listen  80;
        server_name     lokka.local;
        location / {
                if (-f $request_filename) { break; }
                proxy_set_header X-Real-IP  $remote_addr;
                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                proxy_set_header Host $http_host;
                proxy_pass http://unicorn-lokka;
        }
}</pre>
				<p>nginx を再起動する。</p>
				<pre class="brush: bash; title: ; notranslate">/usr/local/nginx/sbin/nginx -s stop
/usr/local/nginx/sbin/nginx</pre>
				<h2>参考文献</h2>
				<ul>
				<li><a href="http://d.hatena.ne.jp/tkng/20100707/1278517873" target="_blank">UnicornでSinatraアプリをデプロイしてみた &#8211; 射撃しつつ前転</a></li>
				</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.cocoalife.net/2010/10/post_851.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

