<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">

 <title>TrikeApps Blog</title>
 <link href="http://blog.trikeapps.com/atom.xml" rel="self"/>
 <link href="http://blog.trikeapps.com/"/>
 <updated>2011-11-20T21:48:55-08:00</updated>
 <id>http://blog.trikeapps.com/</id>
 <author>
   <name>TrikeApps</name>
   <email>it@trikeapps.com</email>
 </author>

 
 <entry>
   <title>Per Request Cache for Rack</title>
   <link href="http://blog.trikeapps.com/2011/11/16/rack-per_request_cache"/>
   <updated>2011-11-16T00:00:00-08:00</updated>
   <id>http://blog.trikeapps.com/2011/11/16/rack-per_request_cache</id>
   <content type="html">&lt;p&gt;
  Ever wanted a cache that is bound to the current request? Check out
  our new gem:
  &lt;a href=&quot;http://github.com/tricycle/rack-per_request_cache&quot; rel=&quot;external&quot; target=&quot;_blank&quot;&gt;Rack::PerRequestCache&lt;/a&gt;.
&lt;/p&gt;

&lt;h2&gt;Installation &amp; Usage&lt;/h2&gt;
&lt;pre&gt;&lt;code&gt;
  gem install rack-per_request_cache
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;
  Have a look at the
  &lt;a href=&quot;http://github.com/tricycle/rack-per_request_cache&quot; rel=&quot;external&quot; target=&quot;_blank&quot;&gt;Readme&lt;/a&gt;
  to see how it's used!
&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Daemonize a script or worker in Rails 3</title>
   <link href="http://blog.trikeapps.com/2011/05/12/daemonize-rails-3-scripts"/>
   <updated>2011-05-12T00:00:00-07:00</updated>
   <id>http://blog.trikeapps.com/2011/05/12/daemonize-rails-3-scripts</id>
   <content type="html">&lt;p&gt;
  A couple of gems allow the easy daemonisation of scripts
  / long running processes. But as soon as you need to
  include your Rails environment you might run into problems.
&lt;/p&gt;

&lt;h2&gt;The problem&lt;/h2&gt;
&lt;p&gt;
  Take this script for example (which lives in
  &lt;code&gt;script/ruote_worker.rb&lt;/code&gt;):
&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;
  require 'daemons'
  require File.expand_path(File.join(File.dirname(__FILE__),
  	'..', 'config', 'environment'))

  Daemons.run_proc('ruote_worker') do
    RuoteKit.run_worker(RuoteSetup.ruote_storage)
  end	
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;
  Looks pretty straightforward - The
  &lt;a href=&quot;http://daemons.rubyforge.org/&quot; rel=&quot;external&quot; target=&quot;_blank&quot;&gt;daemons gem&lt;/a&gt;
  provides a &lt;code&gt;run_proc&lt;/code&gt; method which daemonises the
  given block. But as soon as the ruote worker tries to
  write something to the log-file we get an
  &lt;code&gt;IOError: closed stream&lt;/code&gt; exception. 
&lt;/p&gt;

&lt;h2&gt;Rails 3 wants the log file to itself&lt;/h2&gt;
&lt;p&gt;
  After some research it seems like Rails doesn't
  like it, when
  &lt;a href=&quot;http://stackoverflow.com/questions/5809678/rails-3-daemons-gem-exception-when-querying-model&quot; rel=&quot;external&quot; target=&quot;_blank&quot;&gt;multiple processes have a handle on the log file(s)&lt;/a&gt;.
  As the response in the linked question correctly points out, the solution is to
  instantiate a new logger... with one addition: If your process
  is using &lt;code&gt;ActiveRecord&lt;/code&gt;, we need to re-assign the
  &lt;code&gt;ActiveRecord.logger&lt;/code&gt; as well:
&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;
  require 'daemons'
  require File.expand_path(File.join(File.dirname(__FILE__),
  	'..', 'config', 'environment'))
  require 'ruote/part/smtp_participant'

  Daemons.run_proc('ruote_worker') do
    ruote_logger = ActiveSupport::BufferedLogger.new(
    	File.join(Rails.root, &quot;log&quot;, &quot;ruote_worker.log&quot;))
    Rails.logger = ruote_logger
    ActiveRecord::Base.logger = ruote_logger
  
    RuoteKit.run_worker(RuoteSetup.ruote_storage)
  end
&lt;/code&gt;&lt;/pre&gt;
</content>
 </entry>
 
 <entry>
   <title>Our new TrikeApps office</title>
   <link href="http://blog.trikeapps.com/2011/01/17/new-trikeapps-office"/>
   <updated>2011-01-17T00:00:00-08:00</updated>
   <id>http://blog.trikeapps.com/2011/01/17/new-trikeapps-office</id>
   <content type="html">&lt;p&gt;
  At the start of the year we moved into our new office.
  It's not far away from the old office... but way bigger!
&lt;/p&gt;

  &lt;p class=&quot;center&quot;&gt;
    &lt;img src=&quot;/images/office1.jpg&quot;&gt;
  &lt;/p&gt;

  &lt;p class=&quot;center&quot;&gt;
    &lt;img src=&quot;/images/office2.jpg&quot;&gt;
  &lt;/p&gt;

  &lt;p class=&quot;center&quot;&gt;
    &lt;img src=&quot;/images/office3.jpg&quot;&gt;
  &lt;/p&gt;

  &lt;p class=&quot;center&quot;&gt;
    &lt;img src=&quot;/images/office4.jpg&quot;&gt;
  &lt;/p&gt;

  &lt;p class=&quot;center&quot;&gt;
    &lt;img src=&quot;/images/office5.jpg&quot;&gt;
  &lt;/p&gt;

  &lt;p class=&quot;center&quot;&gt;
    &lt;img src=&quot;/images/office6.jpg&quot;&gt;
  &lt;/p&gt;

</content>
 </entry>
 
 <entry>
   <title>Secure your forms with a simple Math Captcha</title>
   <link href="http://blog.trikeapps.com/2010/12/20/secure-form-with-math-captcha"/>
   <updated>2010-12-20T00:00:00-08:00</updated>
   <id>http://blog.trikeapps.com/2010/12/20/secure-form-with-math-captcha</id>
   <content type="html">&lt;p&gt;
  As soon as your application has a form that's available to everyone,
  you WILL be spammed! So what can we do about it? Well, one option is to
  have all forms secured by authentication... OR we can use a captcha.
&lt;/p&gt;
&lt;p&gt;
  As always, there are a couple of plugins / gems out there that do the traditional
  image captcha (you know, the beautiful images with random text on it).
  The problem is though, some of them suck: Some look hideous
  (like &lt;a href=&quot;https://github.com/ambethia/recaptcha&quot; rel=&quot;external&quot; target=&quot;_blank&quot;&gt;recaptcha&lt;/a&gt;)
  and others require a lot of effort to set up
  (see &lt;a href=&quot;http://expressica.com/simple_captcha/&quot; rel=&quot;external&quot; target=&quot;_blank&quot;&gt;simple captcha&lt;/a&gt;).
&lt;/p&gt;

&lt;h2&gt;What are the options?&lt;/h2&gt;
&lt;p&gt;
  Basic Math! Asking a (really) simple mathematical question will prevent spam,
  because stupid bots are just to stupid to answer it :)
&lt;/p&gt;
&lt;p&gt;
  What do we need for a math captcha? Basically a generator to
  create a question and a two-way hashing algorithm to encode
  (and later decode) the question/answer. Here's the code
  (in a rails app, you want to place this class into the lib folder):
&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;
  require 'ezcrypto'

  class MathCaptcha
    CIPHER_KEY  = &quot;secret key&quot;
    CIPHER_SALT = &quot;secret salt&quot;

    attr_reader :a, :b, :operator

    def initialize
      @a        = (1..10).to_a.rand
      @b        = (1..10).to_a.rand
      @operator = [:+, :*].rand
    end

    def initialize_from(secret)
      yml = YAML.load(key.decrypt64(secret))
      @a, @b, @operator = yml[:a], yml[:b], yml[:operator]
    end

    def correct?(value)
      result == value.to_i
    end

    def encrypt
      key.encrypt64 to_yaml
    end

    def self.decrypt(secret)
      result = new
      result.initialize_from secret
      result
    end

    def question
      &quot;#{@a} #{@operator.to_s} #{@b} = ?&quot;
    end

  protected

    def to_yaml
      YAML::dump({
        :a        =&gt; @a,
        :b        =&gt; @b,
        :operator =&gt; @operator
      })
    end

  private

    def key
      EzCrypto::Key.with_password CIPHER_KEY, CIPHER_SALT
    end

    def result
      @a.send @operator, @b
    end
  end
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;
  The only interesting thing here is the code in the &lt;code&gt;encrypt&lt;/code&gt;
  and &lt;code&gt;decrypt&lt;/code&gt; methods. Basically, what we do is
  dump the relevant variables into a string using YAML and then encrypt/decrypt it
  using &lt;a href=&quot;https://github.com/pelle/ezcrypto&quot; rel=&quot;external&quot; target=&quot;_blank&quot;&gt;ezcrypto&lt;/a&gt;.
&lt;/p&gt;

&lt;h2&gt;Integrating the captcha into the controller and view&lt;/h2&gt;
&lt;p&gt;
  Since our &lt;code&gt;MathCaptcha&lt;/code&gt; already defines all the interface methods
  we need, the integration is straightforward. First the view
  (note how we use the encrypted question):
&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;
  / ... other form code
  %p
    = hidden_field_tag :captcha_secret, @captcha.encrypt
    = label_tag :captcha, @captcha.question
    = text_field_tag :captcha, &quot;&quot;
  %p
    = submit_tag &quot;Send&quot;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;
  And the controller is easy as well. All we do is to intantiate
  the &lt;i&gt;same&lt;/i&gt; captcha question with the use of the secret:
&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;
  require 'math_captcha'

  class ContactsController &lt; ApplicationController

    def new
      @captcha = MathCaptcha.new
    end

    def create
      @captcha = MathCaptcha.decrypt(params[:captcha_secret])

      unless @captcha.correct?(params[:captcha])
        flash.now[:alert] = &quot;Please make sure you answered the math question correct&quot;
        render :new
      else
        ContactsMailer.question(contact).deliver

        flash[:notice] = &quot;Thanks for your request. We will be in contact with you shortly&quot;
        redirect_to root_path
      end
    end
  end
&lt;/code&gt;&lt;/pre&gt;
</content>
 </entry>
 
 <entry>
   <title>GData Spreadsheet Gem released</title>
   <link href="http://blog.trikeapps.com/2010/09/01/gdata-spreadsheet-gem"/>
   <updated>2010-09-01T00:00:00-07:00</updated>
   <id>http://blog.trikeapps.com/2010/09/01/gdata-spreadsheet-gem</id>
   <content type="html">&lt;p&gt;
  Fresh from our office comes the
  &lt;a href=&quot;http://github.com/tricycle/gdata_spreadsheet&quot; rel=&quot;external&quot; target=&quot;_blank&quot;&gt;GData Spreadsheet Gem&lt;/a&gt;.
  This is some logic we extracted from our
  &lt;a href=&quot;http://www.plandeliver.com&quot; rel=&quot;external&quot; target=&quot;_blank&quot;&gt;PlanDeliver&lt;/a&gt; project, to map rows
  in a Google Spreadsheet to Ruby classes. Check out the
  &lt;a href=&quot;http://github.com/tricycle/gdata_spreadsheet&quot; rel=&quot;external&quot; target=&quot;_blank&quot;&gt;github project page&lt;/a&gt;
  for detailed instructions.
&lt;/p&gt;

&lt;h2&gt;Installation&lt;/h2&gt;
&lt;pre&gt;&lt;code&gt;
  gem install gdata_spreadsheet
&lt;/code&gt;&lt;/pre&gt;
</content>
 </entry>
 
 <entry>
   <title>How to get a AuthSub session token for Google's GData</title>
   <link href="http://blog.trikeapps.com/2010/08/19/gdata-authsub"/>
   <updated>2010-08-19T00:00:00-07:00</updated>
   <id>http://blog.trikeapps.com/2010/08/19/gdata-authsub</id>
   <content type="html">&lt;p&gt;
  In the last sprint for our truck routing application
  &lt;a href=&quot;http://www.plandeliver.com&quot; rel=&quot;external&quot; target=&quot;_blank&quot;&gt;PlanDeliver&lt;/a&gt; we focused in large
  parts on making the app talk to a Google Spreadsheet. The idea is, that users can create/update
  orders in the Spreadsheet, which are then imported into the actual PlanDeliver interface. The
  spreadsheet on the other hand, receives live status updates of the orders, eg. about the allocation status.
&lt;/p&gt;
&lt;p&gt;
  As the integration library of choice we went for the excellent
  &lt;a href=&quot;http://code.google.com/apis/gdata/articles/gdata_on_rails.html&quot; rel=&quot;external&quot; target=&quot;_blank&quot;&gt;GData gem&lt;/a&gt;
  which wraps around a handful of Google APIs. Now, one of the more interesting things when talking to
  Google is Authentication (we &lt;a href=&quot;/2010/07/20/google-federated-login.html&quot;&gt;discussed that before&lt;/a&gt;), fairly well
  explained in the
  &lt;a href=&quot;http://code.google.com/apis/gdata/articles/gdata_on_rails.html#Authentication&quot; rel=&quot;external&quot; target=&quot;_blank&quot;&gt;GData on Rails tutorial&lt;/a&gt;.
  For those who don't want to read the whole tutorial: Basically, there are two methods available.
  The simple solution is to use username and password, the other option would be token based authentication.
&lt;/p&gt;

&lt;h2&gt;Fail at first&lt;/h2&gt;
&lt;p&gt;
  Since we're pragmatic, we went with the easy solution first:
&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;
  client = GData::Client::Spreadsheets.new(:version =&gt; '3', :source =&gt; 'PlanDeliver')
  client.clientlogin('[google account email]', '[password]')
&lt;/code&gt;&lt;/pre&gt;
&lt;/p&gt;This worked fine when testing, but as soon as more people started using the feature, Google shut us down -
  apparently the number of authentications (per second) for one account is limited.
  So we started thinking about the token based option, named AuthSub. The good thing about AuthSub is, that you can
  create a 'session'-token which never expires! The bad thing is, that the whole token generation workflow
  is based on a request / response cycle which didn't work for us, because our GData integration is 100% backend...
&lt;/p&gt;

&lt;h2&gt;Sinatra to the rescue&lt;/h2&gt;
&lt;p&gt;
  So we had to get a session token, but our app wasn't setup to get one. Of course, we could have added a controller
  to PlanDeliver to make it happen, but that would have created a lot of overhead:
  branching, merging, testing, deploying, reverting, ...
  So we decided to write up a very small Sinatra app that works as the endpoint for the Google authrorisation
  request and dumps the generated token somewhere. Here's all the code we need:
&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;
  [config.ru]

  require 'rubygems'
  require 'sinatra'

  root_dir = File.dirname(__FILE__)

  set :environment, ENV['RACK_ENV'].to_sym
  set :root, root_dir
  set :app_file, File.join(root_dir, 'authsub.rb')

  disable :run

  require 'authsub'
  run Sinatra::Application
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;
  [authsub.rb]

  require 'rubygems'
  require 'sinatra'
  require 'gdata'

  get &quot;/upgrade_token&quot; do
    client = GData::Client::Spreadsheets.new(:version =&gt; '3', :source =&gt; 'PlanDeliver')
    client.authsub_token = params[:token]
    raise client.auth_handler.upgrade.inspect
  end
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;
  Start that up with thin and make it available through apache and you're ready to go!
&lt;/p&gt;

&lt;h2&gt;Creating and using the session token&lt;/h2&gt;
&lt;p&gt;
  In order to actually use the mini-app, we have to use GData once again. This time we generate the URL
  which we have to visit (in a browser) to grant access:
&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;
  scope = 'https://spreadsheets.google.com/feeds/list'
  next_url = 'http://route/to/your/mini/app'
  secure = false
  session = true
  GData::Auth::AuthSub.get_url(next_url, scope, secure, session)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;
  Open the generated URL in a browser, grant access (with the Google account of your choice)
  and watch the logs of the Sinatra app to find the session token. Then, instead of using
  &lt;code&gt;clientlogin&lt;/code&gt;, we can use AuthSub when communicating with Google:
&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;
  client = GData::Client::Spreadsheets.new(:version =&gt; '3', :source =&gt; 'PlanDeliver')
  client.authsub_token = &quot;[session token]&quot;
&lt;/code&gt;&lt;/pre&gt;

&lt;h2&gt;Things on the side&lt;/h2&gt;
&lt;p&gt;
  Note that you need a different token for each Google service, eg. we had to repeat the
  process to get a token linked to the worksheet API (https://spreadsheets.google.com/feeds/worksheets).
&lt;/p&gt;
&lt;p&gt;
  The Sinatra app would be a prime candidate for a
  &lt;a href=&quot;http://labs.headlondon.com/2010/07/skinny-daemons/&quot; rel=&quot;external&quot; target=&quot;_blank&quot;&gt;skinny daemon&lt;/a&gt;.
  Unfortunately the blog post came a day to late - but let us know when you publish (parts of) our code
  as a gem!
&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Simple authentication in Sinatra with Janrain Engage</title>
   <link href="http://blog.trikeapps.com/2010/07/21/sinatra-with-janrain"/>
   <updated>2010-07-21T00:00:00-07:00</updated>
   <id>http://blog.trikeapps.com/2010/07/21/sinatra-with-janrain</id>
   <content type="html">&lt;p&gt;
  Everybody knows &lt;a href=&quot;http://www.sinatrarb.com/&quot; rel=&quot;external&quot; target=&quot;_blank&quot;&gt;Sinatra&lt;/a&gt; and I'm sure
  that almost everybody has played with it. The simplicity of creating an app is just awesome.
  Unfortunately, as soon as the app gets a bit more complicated, and you need a more sophisticated feature -
  say authentication - you can't rely on all the nice plugins available for Rails (eg.
  &lt;a href=&quot;http://github.com/plataformatec/devise&quot; rel=&quot;external&quot; target=&quot;_blank&quot;&gt;devise&lt;/a&gt; or
  &lt;a href=&quot;http://github.com/binarylogic/authlogic&quot; rel=&quot;external&quot; target=&quot;_blank&quot;&gt;authlogic&lt;/a&gt;). So you end
  up either writing something yourself, or using an external solution.
&lt;/p&gt;
&lt;p&gt;
  So, inspired by
  &lt;a href=&quot;http://blog.saush.com/2009/04/25/third-party-user-authentication-with-ruby-in-a-just-few-lines-of-code/&quot; rel=&quot;external&quot; target=&quot;_blank&quot;&gt;this blog post&lt;/a&gt;
  we ended up with a fully functional (and good looking) authentication solution with minimal effort (check out the
  &lt;a href=&quot;http://github.com/tricycle/vote_your_album&quot; rel=&quot;external&quot; target=&quot;_blank&quot;&gt;full source&lt;/a&gt;).
&lt;/p&gt;

&lt;h2&gt;Setup&lt;/h2&gt;
&lt;p&gt;
  Sign up for
  &lt;a href=&quot;http://www.janrain.com/products/engage&quot; rel=&quot;external&quot; target=&quot;_blank&quot;&gt;Janrain Engage&lt;/a&gt; first and walk through the
  wizard that sets up your account. Fortunately the basic version is free (and that's all you really need for an in-house app).
  The only thing at this point that links Engage to your app, is the token URL you have to specify in the wizard. We skip
  over all the other configuration options here, because they aren't necessary to make the sign-in work.
&lt;/p&gt;

&lt;h2&gt;Authentication in less than 30 lines of ruby code&lt;/h2&gt;
&lt;p&gt;
  In our code, we need an endpoint for Engage. This should (of course) map to the token URL specified before, so with
  eg. &lt;code&gt;http://example.com/signed-in&lt;/code&gt; you should end up with something like:
&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;
  post &quot;/signed-in&quot; do
    if authenticate(params[:token])
      redirect &quot;/&quot;
    else
      redirect &quot;/sign-in&quot;
    end
  end
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;
  Now to the interesting part, the &lt;code&gt;authenticate&lt;/code&gt; helper:
&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;
  def authenticate(token)
    response = JSON.parse(
      RestClient.post(&quot;https://rpxnow.com/api/v2/auth_info&quot;,
        :token =&gt; token,
        :apiKey =&gt; &quot;[your api key]&quot;,
        :format =&gt; &quot;json&quot;,
        :extended =&gt; &quot;true&quot;
      )
    )

    if response[&quot;stat&quot;] == &quot;ok&quot;
      session[&quot;user&quot;] = response[&quot;profile&quot;][&quot;identifier&quot;]
      return true
    end

    return false
  end
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;
  We pass in the received token and use the beautiful
  &lt;a href=&quot;http://github.com/adamwiggins/rest-client&quot; rel=&quot;external&quot; target=&quot;_blank&quot;&gt;rest client gem&lt;/a&gt; to
  authenticate the user with Engage. The result is a (across all providers) standardised
  &lt;a href=&quot;https://rpxnow.com/docs#profile_data&quot; rel=&quot;external&quot; target=&quot;_blank&quot;&gt;JSON response&lt;/a&gt;. In our case,
  we just store the identifier in the session and the user is authenticated! Now, to make our life easier,
  we add a couple more helper methods:
&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;
  helpers do
    def logged_in?
      !!current_user
    end

    def current_user
      User.first :identifier =&gt; session[&quot;user&quot;]
    end
  end
&lt;/code&gt;&lt;/pre&gt;

&lt;h2&gt;The end result&lt;/h2&gt;
&lt;br /&gt;
&lt;p class=&quot;center&quot;&gt;&lt;img src=&quot;/images/engage.png&quot;&gt;&lt;/p&gt;

</content>
 </entry>
 
 <entry>
   <title>Integrating Google Federated Login with your Rails app</title>
   <link href="http://blog.trikeapps.com/2010/07/20/google-federated-login"/>
   <updated>2010-07-20T00:00:00-07:00</updated>
   <id>http://blog.trikeapps.com/2010/07/20/google-federated-login</id>
   <content type="html">&lt;p&gt;
  When making one of your apps available on the
  &lt;a href=&quot;http://www.google.com/enterprise/marketplace/&quot; rel=&quot;external&quot; target=&quot;_blank&quot;&gt;google apps marketplace&lt;/a&gt;
  and you're not aiming for the
  &lt;a href=&quot;http://code.google.com/googleapps/marketplace/#integrate&quot; rel=&quot;external&quot; target=&quot;_blank&quot;&gt;full integration&lt;/a&gt;,
  pretty much all you have to (or at least should) do, is to allow a user to sign-in to your app using his google account.
  This sounds easier than it actually is, because Google's OpenID - called
  &lt;a href=&quot;http://code.google.com/googleapps/domain/sso/openid_reference_implementation.html&quot; rel=&quot;external&quot; target=&quot;_blank&quot;&gt;Google Federated Login&lt;/a&gt; -
  is not really standard OpenID. Otherwise, using one of the
  &lt;a href=&quot;http://github.com/binarylogic/authlogic_openid&quot; rel=&quot;external&quot; target=&quot;_blank&quot;&gt;existing&lt;/a&gt;
  &lt;a href=&quot;http://github.com/viatropos/authlogic-connect&quot; rel=&quot;external&quot; target=&quot;_blank&quot;&gt;plugins&lt;/a&gt; for
  &lt;a href=&quot;http://github.com/binarylogic/authlogic&quot; rel=&quot;external&quot; target=&quot;_blank&quot;&gt;authlogic&lt;/a&gt; (our authentication framework of choice)
  would have done the trick.
&lt;/p&gt;

&lt;h2&gt;Our way to glory&lt;/h2&gt;
&lt;p&gt;
  We had a look at a couple possible solutions, including writing our own authentication library, or using
  a &lt;a href=&quot;http://www.janrain.com/&quot; rel=&quot;external&quot; target=&quot;_blank&quot;&gt;third-party solution&lt;/a&gt;. But that was
  either to complex, or it didn't exactly provide what we needed. So we ended up changing an
  existing plugins and our good old friend &lt;a href=&quot;/2010/06/07/rails-render-monkeypatching.html&quot;&gt;Dr Monkey Patch&lt;/a&gt;.
&lt;/p&gt;

&lt;h2 id=&quot;authlogic&quot;&gt;Authlogic trickery&lt;/h2&gt;
&lt;p&gt;
  The first thing to notice is, that if you use a fairly recent version of the
  &lt;a href=&quot;http://github.com/rails/open_id_authentication&quot; rel=&quot;external&quot; target=&quot;_blank&quot;&gt;open_id_authentication plugin&lt;/a&gt;
  (which is used by the authlogic-openid plugin and itself uses
  &lt;a href=&quot;http://github.com/josh/rack-openid&quot; rel=&quot;external&quot; target=&quot;_blank&quot;&gt;rack-openid&lt;/a&gt; and
  &lt;a href=&quot;http://github.com/openid/ruby-openid&quot; rel=&quot;external&quot; target=&quot;_blank&quot;&gt;ruby-openid&lt;/a&gt;), binary logic's version
  ain't working - but &lt;a href=&quot;http://github.com/mreinsch/authlogic_openid/tree/master&quot; rel=&quot;external&quot; target=&quot;_blank&quot;&gt;this fork&lt;/a&gt;
  is! And, authlogic's &lt;i&gt;auto_register&lt;/i&gt; feature didn't work for us at all. In theory,
  this should create a user-record whenever a non-existing person authenticates, but in our case, it led to infinite loops,
  because the user validated the session, which then tried to create a user, which validated the session... so we ended up writing
  our own auto-register method (&lt;a href=&quot;#auto_register&quot;&gt;more about that later&lt;/a&gt;).
&lt;/p&gt;
&lt;p&gt;
  Another issue was, that Google Federated Login uses
  &lt;a href=&quot;http://openid.net/specs/openid-attribute-exchange-1_0-05.html&quot; rel=&quot;external&quot; target=&quot;_blank&quot;&gt;Attribute Exchange&lt;/a&gt; (AX)
  with OpenID instead of the more common
  &lt;a href=&quot;http://openid.net/specs/openid-simple-registration-extension-1_0.html&quot; rel=&quot;external&quot; target=&quot;_blank&quot;&gt;Simple Registration Extension&lt;/a&gt; (SReg).
  By specifying required fields in the &lt;code&gt;acts_as_authentic&lt;/code&gt; definition within your user model,
  you can force the use of AX attributes in the request:
&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;
  acts_as_authentic do |c|
    c.logged_in_timeout = 1.hour
    c.openid_required_fields = [
      'http://axschema.org/contact/email',    # Email
      'http://axschema.org/namePerson/first', # First name
      'http://axschema.org/namePerson/last'   # Last name
    ]
  end
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;
  This makes Google happy, but in order to be able to extract the users email and name from the response, we had
  to patch the &lt;code&gt;open_id_authentication&lt;/code&gt; plugin
  (&lt;a href=&quot;http://github.com/tricycle/open_id_authentication&quot; rel=&quot;external&quot; target=&quot;_blank&quot;&gt;our fork&lt;/a&gt;).
  By default the plugin parses the response as SReg, but we needed AX, so the only thing we had to change was
&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;
  OpenID::SReg::Response.from_success_response(response)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;to&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;
  OpenID::AX::FetchResponse.from_success_response(response)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;These two rather small changes will allow your users to authenticate through Google.&lt;/p&gt;

&lt;h2 id=&quot;auto_register&quot;&gt;Auto-Register new users&lt;/h2&gt;
&lt;p&gt;
  As mentioned &lt;a href=&quot;#authlogic&quot;&gt;earlier&lt;/a&gt;, authlogics built-in auto-register function caused some headaches.
  But we needed that feature for a seamless user experience, so we had to implement it ourselves. The easy part was to write
  the code that creates a user:
&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;
  class User
    def self.register_with_openid(openid_identifier, openid_ax_response)
      login = openid_ax_response['http://axschema.org/contact/email'].to_s

      user = User.find_by_login(login)
      user ||= User.new(:login =&gt; login)

      user.openid_identifier = openid_identifier
      user.name = [
        openid_ax_response['http://axschema.org/namePerson/first'],
        openid_ax_response['http://axschema.org/namePerson/last']
      ].select(&amp;:present?).join(' ')

      user.save_without_session_maintenance # otherwise we cause havok!
    end
  end
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;
  Note the last line, which makes sure that we don't care about an associated session - would we just
  call &lt;code&gt;save&lt;/code&gt; we would get an infinite loop as well! After taking care of that, we can go ahead and monkey-patch the
  &lt;code&gt;open_id_authentication&lt;/code&gt; plugin to register a user after successful authentication:
&lt;/p&gt;
&lt;code&gt;&lt;pre&gt;
  def complete_open_id_authentication_with_registration(&amp;block)
    complete_open_id_authentication_without_registration do |result, openid_identifier, registration|
      User.register_with_openid(openid_identifier, registration) unless result.unsuccessful?
      yield result, openid_identifier, registration
    end
  end
  alias_method_chain :complete_open_id_authentication, :registration
&lt;/code&gt;&lt;/pre&gt;
</content>
 </entry>
 
 <entry>
   <title>Make rails render different views for multiple sites</title>
   <link href="http://blog.trikeapps.com/2010/06/07/rails-render-monkeypatching"/>
   <updated>2010-06-07T00:00:00-07:00</updated>
   <id>http://blog.trikeapps.com/2010/06/07/rails-render-monkeypatching</id>
   <content type="html">&lt;p&gt;
  At Trike, we have an app that uses the same code (and instance!) for several clients. The clients need
  the same kind of app, the differences are with the styling and (sometimes) the content.
&lt;/p&gt;

&lt;h2&gt;Our first solution&lt;/h2&gt;
&lt;p&gt;
  Applying different styles is dead easy! Showing different text (or whatever) is easy
  as well and we came up with a workable solution (put this in &lt;code&gt;application_helper.rb&lt;/code&gt;):
&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;
  def render_for_client(partial, options = {})
    return &quot;&quot; unless
      File.exist?(File.join(RAILS_ROOT, &quot;app&quot;, &quot;views&quot;, current_client.name, &quot;_#{partial}.html.erb&quot;))

    render &quot;#{current_client.name}/#{partial}&quot;, options
  end
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This worked quite well for a number of reasons:&lt;/p&gt;
&lt;ol&gt;
  &lt;li&gt;We identified the parts of the app that are client-specific&lt;/li&gt;
  &lt;li&gt;We didn't have to worry about partials that are only used with one client (&lt;code&gt;return &quot;&quot;&lt;/code&gt;)&lt;/li&gt;
  &lt;li&gt;We didn't have to touch the rails internals&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;Nice, but not good enough&lt;/h2&gt;
&lt;p&gt;
  In short: It wasn't perfect. In particular, it happened that we rendered a 'regular' (shared)
  partial when we shouldn't. It was just too easy to call the default &lt;code&gt;render&lt;/code&gt;
  method...
&lt;/p&gt;
&lt;p&gt;
  In fact - the more we thought about it - we realised that it should be the other way around:
  &lt;strong&gt;Rendering a client specific template should be the default!&lt;/strong&gt;
&lt;/p&gt;
&lt;p&gt;
  So we went ahead and discussed ways to overwrite / monkeypatch the &lt;code&gt;ActionView::Base#render&lt;/code&gt;
  method. After a quick spike, this turned out to become extremely tricky, very fast - mainly because
  &lt;code&gt;ActionView::Base#render&lt;/code&gt; is used in almost all controllers and mailers. Actually,
  it handles all kinds of situations: from rendering partials and templates to handling layouts.
&lt;/p&gt;

&lt;h2&gt;Rendering partials - Our Way&lt;/h2&gt;
&lt;p&gt;
  To solve our problem, we had to dig deeper rails internals. And after a while we
  found a method that we could adapt to solve our problem: &lt;code&gt;ActionView::Base#render_partial&lt;/code&gt;.
  So without further talk - this is the module that we ended up including in
  &lt;code&gt;ActionView::Base&lt;/code&gt;:
&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;
  module RenderSafetyNet
    def self.included(base)
      base.class_eval do
        include InstanceMethods
        alias_method_chain :render_partial, :client
      end
    end

    module InstanceMethods
      def render_partial_with_client(options = {})
        if options[:shared_template] || (options[:locals] &amp;&amp; options[:locals].delete(:shared_template))
          render_partial_without_client(options)
        else
          partial_path = options[:partial]

          if (String === partial_path || Symbol === partial_path) &amp;&amp; !options.has_key?(:collection)
            begin
              options[:partial] = prefix_partial_path(partial_path)
              render_partial_without_client(options)
            rescue ActionView::MissingTemplate =&gt; e
              message = e.message + &lt;&lt;-MSG

  We were looking for a client specific template.
  If you really wanted to render a shared template, please specify the option :shared_template =&gt; true
              MSG
              raise e.exception(message)
            end
          else
            render_partial_without_client(options)
          end
        end
      end

      def prefix_partial_path(path)
        &quot;#{client_identifier}/#{path}&quot;
      end
    end
  end
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;
  With the new module, we are able to use render for both situations, rendering shared and client specific templates.
  We also changed what kind of template is called by default. So, if you want to render a client specific template
  you just use render the way it was intended:
&lt;/p&gt;
&lt;code&gt;&lt;pre&gt;
  render &quot;about&quot;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;
  This will then map to the &lt;code&gt;[client_name]/about&lt;/code&gt; template. On the other hand, if you want
  to render a regular file, you are &lt;strong&gt;forced&lt;/strong&gt; to specify an extra option:
&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;
  render &quot;login&quot;, :shared_template =&gt; true
&lt;/code&gt;&lt;/pre&gt;

&lt;h2&gt;Conclusion&lt;/h2&gt;
&lt;p&gt;
  If you look at it from a coders perspective, we ended up with a lot more code -
  with basically the exact same functionality. So why did we do it? Because we have
  'tiny little monkey brains'
  (&lt;a href=&quot;http://twitter.com/matthewfallshaw&quot; rel=&quot;external&quot; target=&quot;_blank&quot;&gt;@mfallshaw&lt;/a&gt;)!
  This code prevents us from making the simple mistake (again) by including client specific, and maybe even confidential, information
  on the wrong site.
&lt;/p&gt;
&lt;p&gt;
  So yes, we have more code than before - but we took responsibility (or debt) away from
  our brains and made sure that we're doing the right things (in the future).
&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Thinking Sphinx with custom joins</title>
   <link href="http://blog.trikeapps.com/2010/05/07/custom-joins-thinking-sphinx"/>
   <updated>2010-05-07T00:00:00-07:00</updated>
   <id>http://blog.trikeapps.com/2010/05/07/custom-joins-thinking-sphinx</id>
   <content type="html">&lt;p&gt;
  Today we tried to add an attribute to our Sphinx index definition that uses an
  association with &lt;code&gt;GROUP BY&lt;/code&gt; and &lt;code&gt;HAVING&lt;/code&gt;. This was our first attempt:
&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;
  # association definition
  has_many :regularly_ordered_by, :class_name =&gt; &quot;Order&quot;,
    :finder_sql =&gt; 'SELECT DISTINCT(orders.user_id)' +
      'FROM orders LEFT OUTER JOIN line_items ON (orders.id = line_items.order_id)' +
      'WHERE line_items.product_id = #{id} AND orders.user_id IS NOT NULL' +
      'GROUP BY orders.user_id HAVING COUNT(*) &gt; 1'

  # index definition
  define_index do
    ...

    has regularly_ordered_by(:user_id), :as =&gt; :regular_for_users

    ...
  end
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;
  Unfortunately, TS generates a huge SQL query to generate the index and uses a &lt;code&gt;GROUP BY&lt;/code&gt;
  clause by default, so it ignores any of the slightly advanced SQL features we needed. After a couple
  hours experimenting we came up with a TS index query, that worked. But this solution was rather ugly,
  because we couldn't rely on TS to generate the config for us anymore.
&lt;/p&gt;
&lt;p&gt;
  So because we're developers, we decided to fork and extend TS - you can get a copy at
  &lt;a href=&quot;http://github.com/tricycle/thinking-sphinx&quot; target=&quot;_blank&quot; rel=&quot;external&quot;&gt;Tricycle's fork of TS&lt;/a&gt;.
  With the extension you can specify any SQL that will be appended after the generated joins.
  In the end, our solution looked something like this:
&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;
  # association definition
  # no association needed

  # index definition
  define_index do
    ...

    has &quot;`temp_regularly_ordered_by`.user_ids&quot;, :as =&gt; :regular_for_users, :type =&gt; :multi

    from &lt;&lt;-SQL
LEFT OUTER JOIN (
  SELECT product_id, GROUP_CONCAT(DISTINCT user_id) user_ids FROM
    (
      SELECT `products`.`id` product_id, `orders`.user_id FROM `products`
        LEFT OUTER JOIN `line_items`
          ON (`products`.`id` = `line_items`.`product_id`)
        LEFT OUTER JOIN `orders`
          ON (`orders`.`id` = `line_items`.`order_id` AND `orders`.user_id IS NOT NULL)
      GROUP BY `products`.id, `orders`.user_id HAVING COUNT(`orders`.id) &gt; 1
      ORDER BY NULL
    ) AS regular_products
  WHERE USER_ID IS NOT NULL
  GROUP BY product_id
) AS `temp_regularly_ordered_by` ON (`temp_regularly_ordered_by`.product_id = `products`.id)
      SQL

    ...
  end
&lt;/code&gt;&lt;/pre&gt;
</content>
 </entry>
 
 <entry>
   <title>Calculating counts for all array items</title>
   <link href="http://blog.trikeapps.com/2010/05/07/array-items-counts"/>
   <updated>2010-05-07T00:00:00-07:00</updated>
   <id>http://blog.trikeapps.com/2010/05/07/array-items-counts</id>
   <content type="html">&lt;p&gt;Ever wondered how often a specific item occurs in an Array?&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;
  &gt;&gt; [1, 2, 1, 3, 4, 2, 1, 1, 3, 5, 5].grep(3).size
  =&gt; 2
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Now, if we take that a step further, we can calculate the counts for all elements:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;
  &gt;&gt; list = [1, 2, 1, 3, 4, 2, 1, 1, 3, 5, 5]
  =&gt; [1, 2, 1, 3, 4, 2, 1, 1, 3, 5, 5]
  &gt;&gt; list.uniq.inject({}) { |res, item| res.merge(item =&gt; list.grep(item).size) }
  =&gt; {5=&gt;2, 1=&gt;4, 2=&gt;2, 3=&gt;2, 4=&gt;1}
&lt;/code&gt;&lt;/pre&gt;
</content>
 </entry>
 
 <entry>
   <title>The Government ...</title>
   <link href="http://blog.trikeapps.com/2010/05/04/the-government-is-not-your-friend"/>
   <updated>2010-05-04T00:00:00-07:00</updated>
   <id>http://blog.trikeapps.com/2010/05/04/the-government-is-not-your-friend</id>
   <content type="html">&lt;p class=&quot;center&quot;&gt;&lt;img src=&quot;/images/government.png&quot; alt=&quot;the Government is not your Friend&quot; /&gt;&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Announcing Rack::ChromeFrame</title>
   <link href="http://blog.trikeapps.com/2010/04/30/announcing-rake-chrome-frame"/>
   <updated>2010-04-30T00:00:00-07:00</updated>
   <id>http://blog.trikeapps.com/2010/04/30/announcing-rake-chrome-frame</id>
   <content type="html">&lt;p&gt;&lt;a href='http://www.google.com/chromeframe'&gt;Google Chrome Frame&lt;/a&gt; is a great way to enable modern browser features without forcing the user to upgrade or switch web browser. Once installed it is activated by either including a meta tag in the &lt;code&gt;head&lt;/code&gt; of each page or by setting a header with the same name and value in responses from the web server. Specifically:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;X-UA-Compatible: chrome=1&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The inclusion of the meta tag or setting the header is a good candidate for &lt;a href='http://wiki.github.com/rack/rack/list-of-middleware'&gt;Rack middleware&lt;/a&gt; as it doesn&amp;#8217;t need to interact with the application at all. A quick search revealed some existing work by &lt;a href='http://twitter.com/LuigiMontanez'&gt;Luigi Montanez&lt;/a&gt; of &lt;a href='http://github.com/sunlightlabs/rack-chromeframe'&gt;sunlightlabs&lt;/a&gt;. This implementation injects the meta tag into html responses. Favouring setting the header I created a very simple rack middleware and bundled it up as Gem. For building and releasing the gem I used &lt;a href='http://rubygems.org/gems/jeweler'&gt;Jeweler&lt;/a&gt;, which made the process totally painless:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;% jeweler rack-chromeframe&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Edit code&amp;#8230;&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;% rake build
% gem push pkg/rack-chromeframe-1.0.0.gem&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The gem is called &lt;a href='http://rubygems.org/gems/rack-chromeframe'&gt;rack-chromeframe&lt;/a&gt; and the &lt;a href='http://github.com/tricycle/rack-chromeframe'&gt;code is on GitHub&lt;/a&gt;.&lt;/p&gt;

&lt;h2 id='using_the_gem'&gt;Using the Gem&lt;/h2&gt;

&lt;h3 id='install'&gt;Install&lt;/h3&gt;

&lt;pre&gt;&lt;code&gt;gem install rack-chromeframe&lt;/code&gt;&lt;/pre&gt;

&lt;h3 id='rails'&gt;Rails&lt;/h3&gt;

&lt;p&gt;To use Rack::ChromeFrame in a Rails project:&lt;/p&gt;

&lt;p&gt;Add the following gem dependency you your &lt;code&gt;config/environment.rb&lt;/code&gt;:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;config.gem &amp;#39;rack-chromeframe&amp;#39;, :lib =&amp;gt; &amp;#39;rack/chrome_frame&amp;#39;&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Then &lt;code&gt;use&lt;/code&gt; the middleware (also in &lt;code&gt;config/environment.rb&lt;/code&gt;):&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;config.middleware.use &amp;quot;Rack::ChromeFrame&amp;quot;&lt;/code&gt;&lt;/pre&gt;

&lt;h3 id='rack'&gt;Rack&lt;/h3&gt;

&lt;p&gt;To use Rack::ChromeFrame in a Rack application (such as Sinatra) add the following to your app:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;gem &amp;#39;rack-chromeframe&amp;#39;
require &amp;#39;rack/chromeframe&amp;#39;

use Rack::ChromeFrame,

run app&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;That&amp;#8217;s it! Now all your responses will have the &lt;code&gt;X-UA-Compatible&lt;/code&gt; header set to enable Chrome Frame.&lt;/p&gt;</content>
 </entry>
 
 <entry>
   <title>Blogwarming Party</title>
   <link href="http://blog.trikeapps.com/2010/04/28/first-post"/>
   <updated>2010-04-28T00:00:00-07:00</updated>
   <id>http://blog.trikeapps.com/2010/04/28/first-post</id>
   <content type="html">&lt;p&gt;G'Day.&lt;/p&gt;
&lt;p&gt;We are awesome!&lt;/p&gt;
&lt;p&gt;Having said that, we are also a boutique development shop specialising in web applications written in Ruby (look &lt;a href=&quot;http://radiopaedia.org&quot;&gt;here&lt;/a&gt;, &lt;a href=&quot;http://kandodental.com.au&quot;&gt;here&lt;/a&gt; or &lt;a href=&quot;http://www.plandeliver.com&quot;&gt;here&lt;/a&gt;).&lt;/p&gt;
&lt;p&gt;We'll be sharing all the challenging (or otherwise interesting) stuff that we stumble upon during our day to day work on this blog... Enjoy!&lt;/p&gt;
</content>
 </entry>
 
</feed>

