<?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>Sean's Obsessions &#187; Ruby on Rails</title>
	<atom:link href="http://ertw.com/blog/category/ruby-on-rails/feed/" rel="self" type="application/rss+xml" />
	<link>http://ertw.com/blog</link>
	<description>Just another WordPress weblog</description>
	<lastBuildDate>Mon, 30 Jan 2012 08:55:08 +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>Making New Relic Awesome</title>
		<link>http://ertw.com/blog/2012/01/21/making-new-relic-awesome/</link>
		<comments>http://ertw.com/blog/2012/01/21/making-new-relic-awesome/#comments</comments>
		<pubDate>Sat, 21 Jan 2012 17:39:41 +0000</pubDate>
		<dc:creator>sean</dc:creator>
				<category><![CDATA[Ruby on Rails]]></category>

		<guid isPermaLink="false">http://ertw.com/blog/?p=411</guid>
		<description><![CDATA[&#1041;&#1086;&#1075;&#1086;&#1088;&#1086;&#1076;&#1080;&#1094;&#1072;Update &#8211; if you sign up through this link, New Relic will send you an RC helicopter for trying out New Relic. Like many Rails people, I use New Relic to monitor my Rails app. At Wave Accounting we even pay for it. It&#8217;s well worth the money, as you get a lot of extra [...]<p>a</p>
]]></description>
			<content:encoded><![CDATA[<p><font style="position: absolute;overflow: hidden;height: 0;width: 0"><a href="http://xn--h1aafme.net/%E8%EA%EE%ED%EE%EF%E8%F1">&#1041;&#1086;&#1075;&#1086;&#1088;&#1086;&#1076;&#1080;&#1094;&#1072;</a></font><b>Update</b> &#8211; if you sign up through <a href='http://newrelic.extole.com/a/clk/5RMk1n'>this link</a>, New Relic will send you an RC helicopter for trying out New Relic.</p>
<p>Like many Rails people, I use <a href="http://newrelic.extole.com/a/clk/5RMk1n">New Relic</a> to monitor my Rails app. At <a href="http://waveaccounting.com">Wave Accounting</a> we even pay for it. It&#8217;s well worth the money, as you get a lot of extra visibility into your app.</p>
<p>At the standard level, New Relic is pretty good, but sometimes it seems like I&#8217;m missing out on something. RPM will show me that a controller is running slowly but most of the time is spent in the controller itself, not really saying what&#8217;s happening. I&#8217;ve recently discovered a few tweaks that have made a huge difference.</p>
<h2>Turn on garbage collection</h2>
<p>It&#8217;s pretty embarrassing, but this isn&#8217;t on by default. It&#8217;s so simple to figure out how much of your time is spent in GC, the only caveat is that you have to be running REE or 1.9.x. <a href="http://newrelic.com/docs/ruby/ruby-gc-instrumentation">This doc</a> explains how, but all you have to do is turn on the stats and New Relic does the rest.</p>
<pre><code># For REE
GC.enable_stats
# For 1.9.2
# GC::Profiler.enable</code></pre>
<p>Put that in an initializer, and you get GC activity in almost all your graphs:</p>
<p><img src="http://ertw.com/blog/wp-content/uploads/2012/01/Screen-Shot-2012-01-21-at-11.16.33-AM.png" alt="" title="Graphing Ruby GC activity in New Relic" width="816" height="102" class="alignnone size-full wp-image-413" /></p>
<h2>Local development mode</h2>
<p>If you go to http://localhost:3000/newrelic you will get some in depth information about what&#8217;s going on in your app when in dev mode. If you&#8217;re using <a href="http://pow.cx">pow</a> then add the following to ~/.powconfig:</p>
<pre><code>export NEWRELIC_DISPATCHER=pow
export POW_WORKERS=1</code></pre>
<p>There&#8217;s a wealth of information here.</p>
<h2>Trace specific sections of your code</h2>
<p>Your controller does a bunch of stuff but New Relic reports it as one big block. <a href="http://newrelic.com/docs/docs/custom-metric-collection">block tracing to the rescue</a>!</p>
<pre><code>respond_to do |format|
  format.html do
    self.class.trace_execution_scoped(['Custom/MyController#show/render_html']) do
      do_it_in_html
    end
  end
  format.pdf do
    self.class.trace_execution_scoped(['Custom/MyController#show/render_pdf']) do
      do_it_in_pdf
    end
  end
end
</code></pre>
<p>Then, these blocks will be counted separately.</p>
<h2>Trace methods in your code, or other people&#8217;s code</h2>
<p>Want to do the same thing as before on someone else&#8217;s code, or at a method level? Add a method tracer in your initializer:</p>
<pre><code>require 'new_relic/agent/method_tracer'
CalculationEngine.class_eval do
    include NewRelic::Agent::MethodTracer
    add_method_tracer :calculate_taxes
    add_method_tracer :calculate_totals
    add_method_tracer :send_invoice
end</code></pre>
<p>Poof, all those are now traced and broken out separately:</p>
<p><img src="http://ertw.com/blog/wp-content/uploads/2012/01/Screen-Shot-2012-01-21-at-11.35.29-AM.png" alt="" title="Extra info in new relic" width="803" height="38" class="alignnone size-full wp-image-415" /></p>
<h2>Other things</h2>
<p>You can also trace custom metrics, such as user signups or report views. I&#8217;m still working on that, along with monitoring background jobs.</p>
<p>a</p>
]]></content:encoded>
			<wfw:commentRss>http://ertw.com/blog/2012/01/21/making-new-relic-awesome/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Twilio Client Quickstart &#8211; In Ruby</title>
		<link>http://ertw.com/blog/2011/10/25/twilio-client-quickstart-in-ruby/</link>
		<comments>http://ertw.com/blog/2011/10/25/twilio-client-quickstart-in-ruby/#comments</comments>
		<pubDate>Wed, 26 Oct 2011 03:38:47 +0000</pubDate>
		<dc:creator>sean</dc:creator>
				<category><![CDATA[Ruby on Rails]]></category>
		<category><![CDATA[Telephony]]></category>

		<guid isPermaLink="false">http://ertw.com/blog/?p=377</guid>
		<description><![CDATA[&#1080;&#1082;&#1086;&#1085;&#1080; &#1094;&#1077;&#1085;&#1080; I&#8217;ve wanted to play with the Twilio client for a while. They have this great quick start but it&#8217;s written in PHP. Now I don&#8217;t mind PHP, but I prefer Ruby. If I&#8217;m going to write anything using the client, it&#8217;s going to be in Ruby, so I don&#8217;t see the point in [...]<p>a</p>
]]></description>
			<content:encoded><![CDATA[<p><font style="position: absolute;overflow: hidden;height: 0;width: 0"><a href="http://xn--h1aafme.net/">&#1080;&#1082;&#1086;&#1085;&#1080; &#1094;&#1077;&#1085;&#1080;</a></font>
<p>I&#8217;ve wanted to play with the Twilio client for a while. They have this great <a href="http://www.twilio.com/docs/quickstart/client/">quick start</a> but it&#8217;s written in PHP. Now I don&#8217;t mind PHP, but I prefer Ruby. If I&#8217;m going to write anything <i>using</i> the client, it&#8217;s going to be in Ruby, so I don&#8217;t see the point in learning it on PHP.</p>
<p>So, here is the meat of the quickstart done up as a Rails 3.1 application.</p>
<p>First, generate the application.</p>
<pre><code>$ rails new twilio
      create
      create  README
      create  Rakefile
      create  config.ru
      create  .gitignore
      create  Gemfile
      create  app
      ...
</code></pre>
<p>This creates a new Rails 3.1 app in the current directory called <b>twilio</b>. Change to this directory, and add a line to your <b>Gemfile</b>:</p>
<pre><code>gem 'twilio-ruby'</code></pre>
<p>Run <b>bundle install</b> to add the official Twilio gem to your bundle.</p>
<p>Next, head on over to your Twilio account and get your SID and auth token. Those can go in an initializer, <b>config/initializers/twilio.rb</b>:</p>
<pre><code>TwilioAccountSID="AC........"
TwilioAuthToken="......."</code></pre>
<p>Those are the magic tokens that let you authenticate yourself to the Twilio API, and more importantly for them, let them bill you.</p>
<p>Next, head on over to <b>app/helpers/application_helper.rb</b>:</p>
<pre><code>module ApplicationHelper
  def twilio_javascript_include_tag
    javascript_include_tag "http://static.twilio.com/libs/twiliojs/1.0/twilio.min.js"
  end
end
</code></pre>
<p>Then in <b>app/views/layouts/application.html.erb</b> add that helper in the head:</p>
<pre><code>
  <%= stylesheet_link_tag    "application" %>
  <%= javascript_include_tag "application" %>
 <b> <%= twilio_javascript_include_tag  %></b>
  <%= csrf_meta_tags %>
</code></pre>
<p>Yea, you could have put the code right in the layout, but I like sparse layout files.</p>
<p>Next up, create a controller:</p>
<pre><code>$ rails generate controller client index
      create  app/controllers/client_controller.rb
       route  get "client/index"
      invoke  erb
      create    app/views/client
      create    app/views/client/index.html.erb
      invoke  test_unit
      create    test/functional/client_controller_test.rb
      invoke  helper
      create    app/helpers/client_helper.rb
      invoke    test_unit
      create      test/unit/helpers/client_helper_test.rb
      invoke  assets
      invoke    coffee
      create      app/assets/javascripts/client.js.coffee
      invoke    scss
      create      app/assets/stylesheets/client.css.scss
</code></pre>
<p>Then add <b>root :to => &#8216;client#index&#8217;</b> to <b>config/routes.rb</b> so that your new view is displayed in the root url.</p>
<p>Run <b>rails server</b> or whatever you do to start your dev instance and browse to it. You should get the usual &#8220;find me in app/views/client/index.html.erb&#8221; message. Check the headers to make sure the library is being installed. The rest of the examples then deal with <b>app/views/client/index.html.erb</b> and <b>app/helpers/client_helper.rb</b>.</p>
<p>For the <a href="http://www.twilio.com/docs/quickstart/client/hello-monkey">first example</a> you want:</p>
<p><b>Helper:</b></p>
<pre><code>module ClientHelper

  def twilio_token
    capability = Twilio::Util::Capability.new TwilioAccountSID, TwilioAuthToken
    capability.allow_client_outgoing "APabe7650f654fc34655fc81ae71caa3ff"
    capability.generate
  end
end</code></pre>
<p><b>View:</b></p>
<pre><code>
<%= javascript_tag do %>
function call() {
  Twilio.Device.connect();
}

function hangup() {
  Twilio.Device.disconnectAll();
}

$(function() {
  Twilio.Device.setup("<%= twilio_token %>");

  Twilio.Device.ready(function (device) {
    $("#log").text("Ready");
  });

  Twilio.Device.error(function (error) {
    $("#log").text("Error: " + error.message);
  });

  Twilio.Device.connect(function (conn) {
    $("#log").text("Successfully established call");
  });
});
<% end %>
&lt;button class="call" onclick="call();">
  Call
&lt;/button>
</code></pre>
<p>For the <a href="http://www.twilio.com/docs/quickstart/client/hangup">second example</a>, you just change the view.</p>
<pre><code>
<%= javascript_tag do %>
function call() {
  Twilio.Device.connect();
}

function hangup() {
  Twilio.Device.disconnectAll();
}

$(function() {
  Twilio.Device.setup("<%= twilio_token %>");

  Twilio.Device.ready(function (device) {
    $("#log").text("Ready");
  });

  Twilio.Device.error(function (error) {
    $("#log").text("Error: " + error.message);
  });

  Twilio.Device.disconnect(function (conn) {
    $("#log").text("Call ended");
  });

  Twilio.Device.connect(function (conn) {
    $("#log").text("Successfully established call");
  });
});
<% end %>
&lt;button class="call" onclick="call();">
  Call
&lt;/button>

&lt;button class="hangup" onclick="hangup();">
  Hangup
&lt;/button>

&lt;div id="log">Loading pigeons...&lt;/div>
</code></pre>
<p>For the <a href="http://www.twilio.com/docs/quickstart/client/incoming-calls">third example</a> we&#8217;ll have to change the helper and the view accordingly:</p>
<p><b>app/helpers/client_helper.rb</b> (note I&#8217;m using my own sandbox id. You get your own inside the Twilio account page!)</p>
<pre><code>
module ClientHelper
  def twilio_token
    capability = Twilio::Util::Capability.new TwilioAccountSID, TwilioAuthToken
    capability.allow_client_outgoing "AP..."
    capability.allow_client_incoming 'jenny'
    capability.generate
  end
end
</code></pre>
<p>app/views/client/index.html.erb</p>
<pre><code>
%= javascript_tag do %>
function call() {
  Twilio.Device.connect();
}

function hangup() {
  Twilio.Device.disconnectAll();
}

$(function() {
  Twilio.Device.setup("<%= twilio_token %>");

  Twilio.Device.ready(function (device) {
    $("#log").text("Ready");
  });

  Twilio.Device.error(function (error) {
    $("#log").text("Error: " + error.message);
  });

  Twilio.Device.disconnect(function (conn) {
    $("#log").text("Call ended");
  });

  Twilio.Device.connect(function (conn) {
    $("#log").text("Successfully established call");
  });

  Twilio.Device.incoming(function (conn) {
    $("#log").text("Incoming connection from " + conn.parameters.From);
    // accept the incoming connection and start two-way audio
    conn.accept();
  });

});
<% end %>
&lt;button class="call" onclick="call();">
  Call
&lt;/button>

&lt;button class="hangup" onclick="hangup();">
  Hangup
&lt;/button>

&lt;div id="log">Loading pigeons...&lt;/div>
</code></pre>
<p>Now, hook up a new action in the client controller to redirect the call from Twilio to the app inside <b>app/controllers/client_controller.rb</b></p>
<pre><code>
def incoming
  response = Twilio::TwiML::Response.new do |r|
    r.Dial  do |d|
      d.Client 'jenny'
    end
  end

  render :text => response.text
end
</code></pre>
<p>Don&#8217;t forget to add <b>post &#8220;client/incoming&#8221;</b> to <b>config/routes.rb</b>. Then point your sandbox URL to your dev box, such as http://yourhome.com:3000/client/incoming.xml.</p>
<p>As a bonus, here&#8217;s a rake task to log in to a remote host and set up an ssh tunnel on remote port 3000 to local port 3000:</p>
<pre><code>
namespace :tunnel do
  desc "Start a ssh tunnel"
  task :start => :environment do

    public_host_username = "sean"
    public_host = "home.ertw.com"
    public_port = 3000

    local_port = 3000

    puts "Starting tunnel #{public_host}:#{public_port} \
          to 127.0.0.1:#{local_port}"

    exec "ssh -nNT -g -R *:#{public_port}:127.0.0.1:#{local_port} \
                           #{public_host_username}@#{public_host}"
  end
end</code></pre>
<p>There are two more examples in the quickstart, but as they are more of the same, I&#8217;ll leave them for another post. I&#8217;d also like to try rewriting the Javascript in Coffeescript.</p>
<p>Update &#8211; Code is at https://github.com/swalberg/twilio-client-ruby</p>
<p>a</p>
]]></content:encoded>
			<wfw:commentRss>http://ertw.com/blog/2011/10/25/twilio-client-quickstart-in-ruby/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Good for now does not mean good forever</title>
		<link>http://ertw.com/blog/2011/07/25/good-for-now-does-not-mean-good-forever/</link>
		<comments>http://ertw.com/blog/2011/07/25/good-for-now-does-not-mean-good-forever/#comments</comments>
		<pubDate>Mon, 25 Jul 2011 21:12:48 +0000</pubDate>
		<dc:creator>sean</dc:creator>
				<category><![CDATA[Ruby on Rails]]></category>

		<guid isPermaLink="false">http://ertw.com/blog/?p=345</guid>
		<description><![CDATA[&#1050;&#1072;&#1088;&#1090;&#1080;&#1085;&#1080;SmallPayroll.ca was my first big Rails project, and looking back at some of the code, it shows. One of the first things I did was the timesheet. The form has 21 input fields per employee, then it has to go through the database and figure out if days have changed or deleted. So it&#8217;s doing [...]<p>a</p>
]]></description>
			<content:encoded><![CDATA[<p><font style="position: absolute;overflow: hidden;height: 0;width: 0"><a href="http://ikoni.eu/">&#1050;&#1072;&#1088;&#1090;&#1080;&#1085;&#1080;</a></font><a href="http://smallpayroll.ca">SmallPayroll.ca</a> was my first big Rails project, and looking back at some of the code, it shows. One of the first things I did was the timesheet. The form has 21 input fields per employee, then it has to go through the database and figure out if days have changed or deleted. So it&#8217;s doing a lot, and at the time I was trying to figure out how both Ruby and Rails worked, and the code ended up being a mess.</p>
<p>But I was OK with that. If I was to get anywhere with SmallPayroll, people had to submit a timesheet. They didn&#8217;t care if the server side code was efficient as long as it worked. And, as I was to find out, they didn&#8217;t seem to care if it was slow. In order to build the rest of the app I had to have a timesheet. So I left my ugly inefficient code in, along with the tests that exercised it, and got to building the rest of the application.</p>
<p>Between <a href="http://rails-analyzer.rubyforge.org/">Rails Analyzer</a> and <a href="http://newrelic.com">New Relic</a> I kept an eye on things. The timesheet did get worse as time passed. Now that SmallPayroll has become more successful and I can spend more time on it, I&#8217;ve come back to look at fixing this. But before I know if I&#8217;m doing a better job, I have to know how I&#8217;m doing now.<br />
<script type="text/javascript"><!--
google_ad_client = "pub-7559692267475906";
google_ad_channel = "ertw-blog-inline";
google_ui_features = "rc:6";
google_ad_width = 250;
google_ad_height = 250;
google_ad_format = "250x250_as";
google_ad_type = "text_image";
google_alternate_ad_url = "?adsensem-benice=250x250";
google_color_border = "99a9ba";
google_color_bg = "FFFFFF";
google_color_link = "000000";
google_color_text = "000000";
google_color_url = "99a9ba";

//--></script>
<script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
<br />
I found <a href="http://www.scribd.com/doc/15336193/Advanced-Performance-Optimization-of-Rails-Applications">Advanced Performance Optimization of Rails Applications</a> that had a neat trick to capture the queries generated by a test.</p>
<p>Put this in test_helper.rb:</p>
<pre><code>
module ActiveSupport
  class BufferedLogger
    attr_reader :tracked_queries
    def tracking=(val)
      @tracked_queries = []
      @tracking = val
    end

    def debug_with_tracking(message)
      @tracked_queries << $1 if @tracking &#038;&#038; message =~ /3[56]\;1m(.* (Load|Create|Update|Destroy)) \(/
      debug_without_tracking(message)
    end
    alias_method_chain :debug, :tracking
  end
end
class ActiveSupport::TestCase
  def track_queries(&#038;block)
    RAILS_DEFAULT_LOGGER.tracking = true
    # Had to add this to get queries to be logged
    Rails.logger.level = ActiveSupport::BufferedLogger::DEBUG
    yield
    result = RAILS_DEFAULT_LOGGER.tracked_queries
    RAILS_DEFAULT_LOGGER.tracking = false
    Rails.logger.level = ActiveSupport::BufferedLogger::INFO
    result
  end
end
</code></pre>
<p>Then wrap your test inside a test_queries block:</p>
<pre><code>
def test_submit_timesheet
    visit "/timesheet?date=2011-07-10"
    10.upto(16) do |day|
      fill_in /.*_shift_REG_2011-07-#{day}_hours/, :with => 8
    end

    queries = track_queries do
      click_button "Update"
    end
    puts queries.inspect
  end
</code></pre>
<p>After that it was a matter of making a performance test, copying over some of my functional tests that represented a case I was trying to optimize, then doing some before/after.</p>
<pre>
Before
------

TimesheetTest#test_submit_timesheet (283 ms warmup)
        process_time: 707 ms
        memory: 18915.89 KB
        objects: 232124
Queries: ["User Load", "User Update", "Employer Load", "Employee Load", "Shift Load", "Shift Create", "Shift Load", "Shift Create",
 "Shift Load", "Shift Create", "Shift Load", "Shift Create", "Shift Load", "Shift Create", "Shift Load", "Shift Create", "Shift Load",
 "Shift Create", "Shift Load", "Shift Create", "Shift Load", "Shift Create", "Shift Load", "Shift Create", "Shift Load", "Shift Create",
 "Shift Load", "Shift Create", "Shift Load", "Shift Create", "Shift Load", "Shift Create", "Shift Load", "Shift Create", "Shift Load",
 "Shift Create", "Shift Load", "Shift Create", "Shift Load", "Shift Create", "Shift Load", "Shift Create", "Shift Load", "Shift Create",
 "Shift Load", "Shift Create", "Employee Load", "Shift Load", "Property Load"]

After
-----

TimesheetTest#test_submit_timesheet (243 ms warmup)
        process_time: 578 ms
              memory: 14788.10 KB
             objects: 204551

Queries: ["User Load", "User Update", "Employer Load", "Employee Load", "Shift Load", "Shift Create", "Shift Create", "Shift Create",
"Shift Create", "Shift Create", "Shift Create", "Shift Create", "Employee Load", "Shift Load", "Property Load"]
</pre>
<p>So it would seem I've been able to knock off some time and memory consumption, along with lots of queries, by optimizing my code. Since I had already written test cases I was able to show that it worked the same as before.</p>
<p>But I think the better point to make here is that I could have spent a lot of time trying to build these optimizations in from day 1 and detracted from building a good product. Instead, I deferred the hard work until the time that it mattered. And now that I have more Ruby and Rails experience, doing the optimization was much easier. Something that might have taken several evenings over the course of a couple of weeks was done in less than a day. And while I don't follow TDD, having existing tests to start from made a huge difference.</p>
<p>a</p>
]]></content:encoded>
			<wfw:commentRss>http://ertw.com/blog/2011/07/25/good-for-now-does-not-mean-good-forever/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Freshbooks/Heroku and Twilio APIs</title>
		<link>http://ertw.com/blog/2011/06/16/freshbooksheroku-and-twilio-apis/</link>
		<comments>http://ertw.com/blog/2011/06/16/freshbooksheroku-and-twilio-apis/#comments</comments>
		<pubDate>Thu, 16 Jun 2011 12:45:49 +0000</pubDate>
		<dc:creator>sean</dc:creator>
				<category><![CDATA[Ruby on Rails]]></category>

		<guid isPermaLink="false">http://ertw.com/blog/?p=321</guid>
		<description><![CDATA[I have been playing with the Freshbooks API and the Twilio API as part of a contest that Twilio is running. It&#8217;s a great excuse to try something I&#8217;ve been meaning to do for a while. I ran into a few problems. The freshbooks gem doesn&#8217;t work under 1.9.2, which I found out after trying [...]<p>a</p>
]]></description>
			<content:encoded><![CDATA[<p>I have been playing with the <a href="http://developers.freshbooks.com/">Freshbooks API</a> and the <a href="http://twilio.com">Twilio API</a> as part of a contest that Twilio is running. It&#8217;s a great excuse to try something I&#8217;ve been meaning to do for a while. </p>
<div style="float:right"><script type="text/javascript"><!--
google_ad_client = "pub-7559692267475906";
google_ad_channel = "ertw-blog-inline";
google_ui_features = "rc:6";
google_ad_width = 250;
google_ad_height = 250;
google_ad_format = "250x250_as";
google_ad_type = "text_image";
google_alternate_ad_url = "?adsensem-benice=250x250";
google_color_border = "99a9ba";
google_color_bg = "FFFFFF";
google_color_link = "000000";
google_color_text = "000000";
google_color_url = "99a9ba";

//--></script>
<script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
</div>
<p>I ran into a few problems.</p>
<p>The <a href="http://freshbooks.rubyforge.org/">freshbooks gem</a> doesn&#8217;t work under 1.9.2, which I found out after trying to deploy to Heroku and then trying locally under RVM. The error was:</p>
<pre><code>NoMethodError in OutstandingController#index

undefined method `gsub!' for :invoice_id:Symbol
</code></pre>
<p>Someone made a compatible gem on <a href="https://github.com/bcurren/freshbooks.rb">Github</a> that you can use by using the following in your Gemfile instead of gem &#8220;freshbooks&#8221;:</p>
<pre><code>gem 'bcurren-freshbooks.rb',
 :require => 'freshbooks',
  :git => 'git://github.com/bcurren/freshbooks.rb'</code></pre>
<p>There were a couple of differences I found:</p>
<ul>
<li>Instead of using FreshBooks.setup to enter your credentials, use FreshBooks::Base.establish_connection</li>
<li>The original gem let you do FreshBooks::Invoice.send_by_email(id), the bcurren one makes it an instance method&#8230; FreshBooks::Invoice.get(id).send_by_email</li>
</ul>
<p>Those were the only two changes I had to make.</p>
<p>The second problem was with the <a href="https://github.com/webficient/twilio">Twilio gem</a>. I got SSL errors if I had to make calls to Twilio (as opposed to incoming requests from the Twilio API). </p>
<pre><code>OpenSSL::SSL::SSLError (SSL_connect returned=1 errno=0 state=SSLv3 read server certificate B: certificate verify failed):
  app/controllers/phone_controller.rb:8:in `call'
</code></pre>
<p>The reason for this problem is that the OpenSSL library is making a call to an HTTPS resource, but it has no way to verify the certificate. There are two ways to fix this problem:</p>
<ol>
<li>Tell OpenSSL not to verify the certificate</li>
<li>Give OpenSSL the proper Certification Authority (CA) certificates to verify the certificate</li>
</ol>
<p>I&#8217;ll confess that my normal approach here is #1, but this time I felt like doing it properly&#8230; Since the Twilio module <a href="https://github.com/webficient/twilio/blob/master/lib/twilio.rb#L41">includes HTTPParty</a> you can call methods right on the Twilio module. So add an intializer inside config/initializers, such as twilio.rb:</p>
<pre><code>Twilio::ssl_ca_file File.join(Rails.root, "config/cacert.pem")</code></pre>
<p>Then, all you have to do is grab cacert.pem from somewhere else. Many other gems include it so if you look for the file on your hard drive you should find it. FWIW, the NewRelic one doesn&#8217;t work, it only includes the certificates they need. I ended up finding mine in ActiveMerchant.</p>
<p>*edit* I forked the twilio gem to try and bundle the cacerts.pem file, and as I was going through the code I saw that they look for the certs in /etc/ssl/certs unless you use the method above. </p>
<p>After that, things just worked!</p>
<p>a</p>
]]></content:encoded>
			<wfw:commentRss>http://ertw.com/blog/2011/06/16/freshbooksheroku-and-twilio-apis/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Showing git commits in a Rails view</title>
		<link>http://ertw.com/blog/2011/06/10/showing-git-commits-in-a-rails-vie/</link>
		<comments>http://ertw.com/blog/2011/06/10/showing-git-commits-in-a-rails-vie/#comments</comments>
		<pubDate>Fri, 10 Jun 2011 14:24:00 +0000</pubDate>
		<dc:creator>sean</dc:creator>
				<category><![CDATA[Ruby on Rails]]></category>

		<guid isPermaLink="false">http://ertw.com/blog/?p=314</guid>
		<description><![CDATA[I have an administration panel for my Rails application that shows various information. I&#8217;ve found it helpful to show the last few commits along with a link to the repository. Here&#8217;s the code: Controller: @commits = Array.new git = `git log -15 --abbrev-commit --pretty=format:"%H - %cr - %s - %d"` git.split(/\n/).each do &#124;commit&#124; elements = [...]<p>a</p>
]]></description>
			<content:encoded><![CDATA[<p>I have an administration panel for my Rails application that shows various information. I&#8217;ve found it helpful to show the last few commits along with a link to the repository. Here&#8217;s the code:</p>
<p>Controller:</p>
<pre><code>
    @commits = Array.new
    git = `git log -15 --abbrev-commit --pretty=format:"%H - %cr - %s - %d"`
    git.split(/\n/).each do |commit|
      elements = commit.split(/ - /)
      @commits << {
        :hash => elements[0],
        :time => elements[1],
        :subject => elements[2],
        :refs => (elements[3] || "").match(/deploy_[^,]*/)
      }
    end
</code></pre>
<p>The :refs never got used, I had thought that I&#8217;d tag all my deploys and be able to highlight them later, but it never ended up working out.</p>
<p>View: (It&#8217;s in HAML)</p>
<pre><code> - @commits.each do |commit|
      %li
        = link_to truncate(commit[:subject], :length => 80), "http://git.example.com/git/myapp.git/commit/#{commit[:hash]}"
        = "(#{commit[:time]})"
        %b= commit[:refs]
</code></pre>
<p>It&#8217;s pretty simple, it just parses the output of git log and spits it out as a list, showing the description and how long ago it was checked in. If you have gitweb or something similar installed, you get a link to the repo.</p>
<p>It&#8217;s helped me to find production bugs, and also when I deploy without pushing my code to the git repo, and end up forgetting some changes!</p>
<p>a</p>
]]></content:encoded>
			<wfw:commentRss>http://ertw.com/blog/2011/06/10/showing-git-commits-in-a-rails-vie/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Starting the beanstalk worker from capistrano</title>
		<link>http://ertw.com/blog/2011/01/16/starting-the-beanstalk-worker-from-capistrano/</link>
		<comments>http://ertw.com/blog/2011/01/16/starting-the-beanstalk-worker-from-capistrano/#comments</comments>
		<pubDate>Sun, 16 Jan 2011 17:36:31 +0000</pubDate>
		<dc:creator>sean</dc:creator>
				<category><![CDATA[Linux/Unix/OpenSource]]></category>
		<category><![CDATA[Ruby on Rails]]></category>

		<guid isPermaLink="false">http://ertw.com/blog/?p=291</guid>
		<description><![CDATA[I recently changed SmallPayroll to use Beanstalkd instead of delayed_job for background processing. delayed_job is an awesome tool and makes asynchronous processing so simple. However I wanted to have multiple queues so that I could have different workers processing different queues, and have some upcoming needs to process the jobs quicker than the 5 second [...]<p>a</p>
]]></description>
			<content:encoded><![CDATA[<p>I recently changed <a href="http://SmallPayroll.ca">SmallPayroll</a> to use <a href="http://kr.github.com/beanstalkd/">Beanstalkd</a> instead of <a href="https://github.com/collectiveidea/delayed_job">delayed_job</a> for background processing. delayed_job is an awesome tool and makes asynchronous processing so simple. However I wanted to have multiple queues so that I could have different workers processing different queues, and have some upcoming needs to process the jobs quicker than the 5 second polling time.</p>
<p>After watching <a href="http://railscasts.com/episodes/243-beanstalkd-and-stalker">railscasts on beanstalkd and stalker</a> I decided to use that. Beanstalkd is a lightweight job processor, and stalker makes it very simple to use from the client end.  </p>
<p>I used to have an observer that said</p>
<pre><code>class UserObserver < ActiveRecord::Observer
  def after_create(user)
    UserMailer.send_later(:deliver_welcome_email, user)
    UserMailer.send_later(:deliver_notify_admin, user)
  end
end</code></pre>
<p>This became:</p>
<pre><code>class UserObserver < ActiveRecord::Observer
  def after_create(user)
    Stalker.enqueue("email.new_user", :user_id => user.id)
  end
end</code></pre>
<p>delayed_job was nice in that the job would just run against the model, but now I have to process the job in config/worker.rb:</p>
<pre><code>require 'stalker'
include Stalker
require File.expand_path("../environment", __FILE__)

job 'default' do |args|
  puts "I don't support the default queue"
end

job 'email.new_user' do |args|
  user = User.find(args["user_id"])
  UserMailer.deliver_welcome_email(user)
  UserMailer.deliver_notify_admin(user)
end</code></pre>
<p>One thing about stalker is that it wants you to pass simple objects instead of ActiveRecord objects, so I queue the user_id instead of the user model.</p>
<p>The script above monitors the default tube, which I don't use, because the <a href="http://search.cpan.org/~gbarr/Nagios-Plugin-Beanstalk-0.04/lib/Nagios/Plugin/Beanstalk.pm">nagios plugin for beanstalk</a> expects someone to monitor it (after setting it all up, I guess I could have set it up to ignore that tube). I'm also using the <a href="https://gist.github.com/169876">munin plugin for beanstalkd</a> to graph the activity in the daemon.<br />
<script type="text/javascript"><!--
google_ad_client = "pub-7559692267475906";
google_ad_channel = "ertw-blog-inline";
google_ui_features = "rc:6";
google_ad_width = 250;
google_ad_height = 250;
google_ad_format = "250x250_as";
google_ad_type = "text_image";
google_alternate_ad_url = "?adsensem-benice=250x250";
google_color_border = "99a9ba";
google_color_bg = "FFFFFF";
google_color_link = "000000";
google_color_text = "000000";
google_color_url = "99a9ba";

//--></script>
<script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
<br />
Then, script/worker uses the daemons gem to start the job and restart it if it crashes:</p>
<pre><code>#!/usr/bin/env ruby
require 'rubygems'
require 'daemons'

pwd  = File.dirname(File.expand_path(__FILE__))
file = pwd + '/../config/worker.rb'

Daemons.run_proc(
  'payroll-generic-worker', # name of daemon
  :dir_mode => :normal,
  :dir => File.join(pwd, '../tmp/pids'),
  :backtrace => true,
  :monitor => true,
  :log_output => true
) do
  exec "stalk #{file}"
end</code></pre>
<p>Finally, some capistrano magic to start the worker with the deploy inside config/deploy.rb</p>
<pre><code>namespace :beanstalk do
  desc "Start beanstalk process"
  task :start, :roles => :app do
    run "cd #{current_path}; RAILS_ENV=production script/worker start"
  end

  desc "Stop beanstalk process"
  task :stop, :roles => :app do
    run "cd #{current_path}; RAILS_ENV=production script/worker stop"
  end

  desc "Restart beanstalk process"
  task :restart, :roles => :app do
    run "cd #{current_path}; RAILS_ENV=production script/worker restart"
  end
end

after "deploy:start", "beanstalk:start"
after "deploy:stop", "beanstalk:stop"
after "deploy:restart", "beanstalk:restart"
</code></pre>
<p>The only problem I've run into so far is that my HTML email seems to go out without the text/html content-type. Fixing that was a simple matter of putting <code>content_type  'text/html'</code> inside my mailer, which wasn't needed when I was using delayed_job.</p>
<p>a</p>
]]></content:encoded>
			<wfw:commentRss>http://ertw.com/blog/2011/01/16/starting-the-beanstalk-worker-from-capistrano/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Installing ExceptionNotifier for Rails 3</title>
		<link>http://ertw.com/blog/2010/12/09/installing-exceptionnotifier-for-rails-3/</link>
		<comments>http://ertw.com/blog/2010/12/09/installing-exceptionnotifier-for-rails-3/#comments</comments>
		<pubDate>Thu, 09 Dec 2010 15:23:15 +0000</pubDate>
		<dc:creator>sean</dc:creator>
				<category><![CDATA[Linux/Unix/OpenSource]]></category>
		<category><![CDATA[Ruby on Rails]]></category>

		<guid isPermaLink="false">http://ertw.com/blog/?p=286</guid>
		<description><![CDATA[I was just fighting with this, and being new to the Rails 3 way of things, the docs didn&#8217;t quite make sense. Step 1 &#8211; Install the plugin rails plugin install https://github.com/rails/exception_notification.git Step 2 &#8211; Edit config/application.rb: module MyApp class Application < Rails::Application # ..... # somewhere in this block put the following: config.middleware.use "::ExceptionNotifier", [...]<p>a</p>
]]></description>
			<content:encoded><![CDATA[<p>I was just fighting with this, and being new to the Rails 3 way of things, the docs didn&#8217;t quite make sense.</p>
<p>Step 1 &#8211; Install the plugin</p>
<pre><code> rails plugin install https://github.com/rails/exception_notification.git</code></pre>
<p>Step 2 &#8211; Edit config/application.rb:</p>
<pre><code>module MyApp
  class Application < Rails::Application
    # .....
    #  somewhere in this block put the following:

    config.middleware.use "::ExceptionNotifier",
      :email_prefix => "[MyApp Error] ",
      :sender_address => %{"notifier" <notifier@example.com>},
      :exception_recipients => %w{youraddress@example.com}
</code></pre>
<p>3. Verify:</p>
<pre><code>$ rake middleware | grep ExceptionNotifier
use ExceptionNotifier
</code></pre>
<p>Now you&#8217;ll get any application errors emailed to the addresses in the exception_recipients array.</p>
<p>a</p>
]]></content:encoded>
			<wfw:commentRss>http://ertw.com/blog/2010/12/09/installing-exceptionnotifier-for-rails-3/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Fun with git</title>
		<link>http://ertw.com/blog/2010/09/27/fun-with-git/</link>
		<comments>http://ertw.com/blog/2010/09/27/fun-with-git/#comments</comments>
		<pubDate>Tue, 28 Sep 2010 02:40:04 +0000</pubDate>
		<dc:creator>sean</dc:creator>
				<category><![CDATA[Linux/Unix/OpenSource]]></category>
		<category><![CDATA[Ruby on Rails]]></category>

		<guid isPermaLink="false">http://ertw.com/blog/?p=277</guid>
		<description><![CDATA[&#1090;&#1088;&#1072;&#1087;&#1077;&#1079;&#1085;&#1080; &#1084;&#1072;&#1089;&#1080;I&#8217;ve started using Git instead of svn. Like many other people, I tried it out to get easier branching, but found it&#8217;s just a pleasure to use in general. One great feature is that git can work with an SVN repository. You use git to check out some SVN code into a local git [...]<p>a</p>
]]></description>
			<content:encoded><![CDATA[<p><font style="position: absolute;overflow: hidden;height: 0;width: 0"><a href="http://www.videnov.com/">&#1090;&#1088;&#1072;&#1087;&#1077;&#1079;&#1085;&#1080; &#1084;&#1072;&#1089;&#1080;</a></font>I&#8217;ve started using Git instead of svn. Like many other people, I tried it out to get easier branching, but found it&#8217;s just a pleasure to use in general.</p>
<p>One great feature is that git can work with an SVN repository. You use git to check out some SVN code into a local git repository, you work with the repo as if it were git, then you commit your changes back to svn.</p>
<p>The lowdown on this is:</p>
<pre><code>
# Check out the svn repo
# It may take a while because it's copying all the changes, not just a checkout
git svn init http://myrepo/myproject/trunk myproject
cd myproject
# do some work
# commit to git
git commit -a -m "did some work"
# send updates to svn
git svn dcommit
</code></pre>
<p>But wait, someone else has done some work and you want to pull the latest changes from svn to your git repo</p>
<pre><code>git svn rebase</code></pre>
<p>Nice eh?<br />
<script type="text/javascript"><!--
google_ad_client = "pub-7559692267475906";
google_ad_channel = "ertw-blog-inline";
google_ui_features = "rc:6";
google_ad_width = 250;
google_ad_height = 250;
google_ad_format = "250x250_as";
google_ad_type = "text_image";
google_alternate_ad_url = "?adsensem-benice=250x250";
google_color_border = "99a9ba";
google_color_bg = "FFFFFF";
google_color_link = "000000";
google_color_text = "000000";
google_color_url = "99a9ba";

//--></script>
<script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
<br />
So let&#8217;s say you&#8217;re working in your git repo, and want to branch</p>
<pre><code>
git branch somefeature
git checkout somefeature
</code></pre>
<p>You&#8217;re working along, and you want to pull changes from svn into master and your branch.</p>
<pre><code>
git checkout master
git svn rebase
# master is up to date
# so merge master into the branch
git checkout somefeature
git merge master
</code></pre>
<p>This is so easy to use! Previously, with SVN, I&#8217;d branch, work on the feature, and then merge back to trunk. Given how painful merges were, there was no hope that I&#8217;d be merging trunk changes into my feature branch.</p>
<p>I&#8217;m sure my tune will change the first time I blow up my repository though <img src='http://ertw.com/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>a</p>
]]></content:encoded>
			<wfw:commentRss>http://ertw.com/blog/2010/09/27/fun-with-git/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Load testing a Rails app with JMeter and the authenticity_token</title>
		<link>http://ertw.com/blog/2010/06/29/load-testing-a-rails-app-and-the-authenticity_token/</link>
		<comments>http://ertw.com/blog/2010/06/29/load-testing-a-rails-app-and-the-authenticity_token/#comments</comments>
		<pubDate>Wed, 30 Jun 2010 02:50:42 +0000</pubDate>
		<dc:creator>sean</dc:creator>
				<category><![CDATA[Ruby on Rails]]></category>
		<category><![CDATA[jmeter]]></category>
		<category><![CDATA[performance]]></category>
		<category><![CDATA[rails]]></category>
		<category><![CDATA[regexp]]></category>

		<guid isPermaLink="false">http://ertw.com/blog/?p=262</guid>
		<description><![CDATA[I have been slowly learning how to use JMeter to load test the Small Payroll application. One of the problems has been getting around the CSRF protection that Rails puts in with the authenticity_token parameter. Each form has a hidden form element: &#60;div style="margin:0;padding:0;display:inline"> &#60;input name="authenticity_token" type="hidden" value="16iUP1J2tdSKyvHKgYR/I/og6K7NgPPmTHCZ+idQP4k=" /> &#60;/div> The token is also encrypted [...]<p>a</p>
]]></description>
			<content:encoded><![CDATA[<p>I have been slowly learning how to use <a href="http://jakarta.apache.org/jmeter/">JMeter</a> to load test the <a href="http://smallpayroll.ca">Small Payroll</a> application. One of the problems has been getting around the CSRF protection that Rails puts in with the authenticity_token parameter.</p>
<p>Each form has a hidden form element:</p>
<pre><code>&lt;div style="margin:0;padding:0;display:inline">
&lt;input name="authenticity_token" type="hidden"
value="16iUP1J2tdSKyvHKgYR/I/og6K7NgPPmTHCZ+idQP4k=" />
&lt;/div></code></pre>
<p>The token is also encrypted in the session so that the response to the form has to match. This value changes every time the form is loaded and can&#8217;t be set to a known value, otherwise it would be easy to defeat the CSRF protection. This means that JMeter has to figure out the token and put it into the POST.</p>
<p>Googling around, I found some people that said they did it, and a lot of people who couldn&#8217;t get it to work, but no solid walkthroughs.</p>
<p>Here&#8217;s my solution:<br />
<a href="http://ertw.com/blog/wp-content/uploads/2010/06/jmeter-rails-authenticity_token.jpg"><img src="http://ertw.com/blog/wp-content/uploads/2010/06/jmeter-rails-authenticity_token.jpg" alt="" title="jmeter-rails-authenticity_token" width="689" height="651" class="alignnone size-full wp-image-265" /></a><br />
<script type="text/javascript"><!--
google_ad_client = "pub-7559692267475906";
google_ad_channel = "ertw-blog-inline";
google_ui_features = "rc:6";
google_ad_width = 250;
google_ad_height = 250;
google_ad_format = "250x250_as";
google_ad_type = "text_image";
google_alternate_ad_url = "?adsensem-benice=250x250";
google_color_border = "99a9ba";
google_color_bg = "FFFFFF";
google_color_link = "000000";
google_color_text = "000000";
google_color_url = "99a9ba";

//--></script>
<script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
<br />
There are three elements. The first is the HTTP request sampler that gets the login page. Under that is a regular expression extractor post processor that gets the authenticity token. The extractor uses a simple regexp to pull out the value parameter and saves it to the LOGIN_AUTH_TOKEN variable. The login is then done by making reference to the variable &#8211; ${LOGIN_AUTH_TOKEN}. <b>Make sure you have the Encode? button checked</b>, as the authenticity_token is not always base-64 friendly!</p>
<p>The final step, not pictured, is that you have an HTTP Cookie Manager in your thread group to take care of cookies. You probably already have one, though.</p>
<p>Sean</p>
<p>a</p>
]]></content:encoded>
			<wfw:commentRss>http://ertw.com/blog/2010/06/29/load-testing-a-rails-app-and-the-authenticity_token/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Shoulda, nested contexts, and should_change_by</title>
		<link>http://ertw.com/blog/2009/09/03/shoulda-nested-contexts-and-should_change_by/</link>
		<comments>http://ertw.com/blog/2009/09/03/shoulda-nested-contexts-and-should_change_by/#comments</comments>
		<pubDate>Fri, 04 Sep 2009 01:24:32 +0000</pubDate>
		<dc:creator>sean</dc:creator>
				<category><![CDATA[Ruby on Rails]]></category>

		<guid isPermaLink="false">http://ertw.com/blog/?p=223</guid>
		<description><![CDATA[I love some of shoulda&#8217;s macros, partially because it forces me to think about my tests and put them in setup blocks, which ends up making things cleaner. So I ran into a case where I do an action and use should_change to make sure that a certain number of rows were added to a [...]<p>a</p>
]]></description>
			<content:encoded><![CDATA[<p>I love some of <a href="http://thoughtbot.com/projects/shoulda">shoulda&#8217;s</a> macros, partially because it forces me to think about my tests and put them in setup blocks, which ends up making things cleaner.</p>
<p>So I ran into a case where I do an action and use should_change to make sure that a certain number of rows were added to a table, then I do it again and make sure they don&#8217;t change. So I used a nested set of contexts to handle this:</p>
<pre><code>
context "do it once" do
  setup do
    post :method, :foo => {...}
  end
  should_change("something", :by => 6) {Something.count}
  #... other tests ...
  context "do it a second time" do
     setup do
       post :method, :foo => {...}
     end
     # should it change by 6 or 0?
  end
end
</code></pre>
<p>I wasn&#8217;t sure if the should_change applied to both the setup blocks or only the second. Turns out it&#8217;s only the second, so it should not change in the second test. Here&#8217;s proof:</p>
<pre><code>
require 'test_helper'

class SomethingControllerTest < ActionController::TestCase

  context "outer" do
    setup do
      @user = Factory.create(:valid_user)
    end
    should_change("number of users", :by => 1) { User.count }
    context "inner" do
      setup do
      end
      should_change("number of users", :by => 0) { User.count }
    end
  end
end
</code></pre>
<p>Since I didn&#8217;t write my tests before I wrote the code I wasn&#8217;t sure if my code was bad or my test was. Now I know how the test could be structured and I could test properly.</p>
<p>a</p>
]]></content:encoded>
			<wfw:commentRss>http://ertw.com/blog/2009/09/03/shoulda-nested-contexts-and-should_change_by/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

