<?xml version="1.0" encoding="UTF-8"?>
<!--Generated by Squarespace Site Server v5.11.81 (http://www.squarespace.com/) on Sun, 20 May 2012 04:34:27 GMT--><rss xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:itunes="http://www.itunes.com/dtds/podcast-1.0.dtd" xmlns:dc="http://purl.org/dc/elements/1.1/" version="2.0"><channel><title>Blog</title><link>http://techblog.kontera.com/blog/</link><description></description><lastBuildDate>Thu, 16 Feb 2012 12:43:18 +0000</lastBuildDate><copyright></copyright><language>en-US</language><generator>Squarespace Site Server v5.11.81 (http://www.squarespace.com/)</generator><item><title>utilities that make unit testing easier</title><dc:creator>Nimrod Beithalachmi</dc:creator><pubDate>Sun, 25 Dec 2011 10:00:26 +0000</pubDate><link>http://techblog.kontera.com/blog/2011/12/25/utilities-that-make-unit-testing-easier.html</link><guid isPermaLink="false">1083858:12546076:13879053</guid><description><![CDATA[<p>Working with an application that requires many resources and services might take a while to initialize.&nbsp;Such is our <a href="http://www.kontera.com/advertisers/ad-gallery"> Kontera Advertisers Center</a>. When working in development mode it is nice to be able to run our <a href="https://github.com/rspec/rspec">Rspec</a> tests. But although the test themselves run fast (about 300 tests in ~30&nbsp;seconds), loading the environment takes 40 seconds. To ease the pain of waiting I use a <em><a href="http://spork.rubyforge.org/">spork</a></em>!</p>
<p>&nbsp;<span class="full-image-block ssNonEditable"><span><img src="http://imgs.xkcd.com/comics/forks_and_spoons.png?__SQUARESPACE_CACHEVERSION=1323033235613" alt="" /></span></span></p>
<p>Image taken from http://imgs.xkcd.com/comics/forks_and_spoons.png</p>
<p>&nbsp;</p>
<p><em>Spork</em> makes running unit tests faster by shortening the loading time. It requires some modifications to your <em>spec_helper.rb</em> file: (example from AC <em>spec/spec_helper.rb</em>)</p>
<pre class="brush:rails; toolbar: false;">require 'spork'

Spork.prefork do
  # Loading more in this block will cause your tests to run faster. However,
  # if you change any configuration or code from libraries loaded here, you'll
  # need to restart spork for it to take effect.
  ENV["RAILS_ENV"] = 'ci'
  $LOAD_PATH.push File.join(File.dirname(__FILE__),"..")
  require File.expand_path(File.join(File.dirname(__FILE__),'..','config','environment'))
  require 'spec/rails'
end
Spork.each_run do
  # This code will be run each time you run your specs.
  Dir[File.expand_path(File.join(File.dirname(__FILE__),'/spec_helpers','**','*.rb'))].each {|f| require f}
end
</pre>
<p>To use <em>Spork</em>: Install <em>spork</em> gem:</p>
<pre class="brush: plain; toolbar: false; gutter: false;">gem install spork</pre>
<p>Bootstap <em>spork</em>: (then modify your <em>spec_helper</em>)</p>
<pre class="brush: plain; toolbar: false; gutter: false;">spork --bootstrap</pre>
<p>Run <em>spork</em> in the background: (from application root)</p>
<pre class="brush: plain; toolbar: false; gutter: false;">spork &amp;</pre>
<p>Add <em>--drb</em> to the running test, for example:</p>
<pre class="brush: plain; toolbar: false; gutter: false;">spec spec/models/permissions.rb -c -fn --drb</pre>
<p>&nbsp;</p>]]></description><wfw:commentRss>http://techblog.kontera.com/blog/rss-comments-entry-13879053.xml</wfw:commentRss></item><item><title>Porting from Ruby 1.8.7 to Ruby 1.9.3: An Oddyssey</title><category>porting</category><category>porting</category><category>rails</category><category>ruby</category><dc:creator>Gil Erlich</dc:creator><pubDate>Sun, 18 Dec 2011 10:00:45 +0000</pubDate><link>http://techblog.kontera.com/blog/2011/12/18/porting-from-ruby-187-to-ruby-193-an-oddyssey.html</link><guid isPermaLink="false">1083858:12546076:13930232</guid><description><![CDATA[sessions_controller.rb:86: syntax error, unexpected ':', expecting keyword_then or ',' or ';' or '\n']]></description><wfw:commentRss>http://techblog.kontera.com/blog/rss-comments-entry-13930232.xml</wfw:commentRss></item><item><title>First Steps on Amazon's CloudWatch</title><category>AWS</category><category>cloud</category><category>cloudwatch</category><category>coding</category><dc:creator>Dan Dimerman</dc:creator><pubDate>Sun, 11 Dec 2011 10:00:22 +0000</pubDate><link>http://techblog.kontera.com/blog/2011/12/11/first-steps-on-amazons-cloudwatch.html</link><guid isPermaLink="false">1083858:12546076:13928399</guid><description><![CDATA[<p>In this post we will go over some of the services offered by <a href="http://aws.amazon.com/">Amazon Web Services</a>, focusing on <a href="http://aws.amazon.com/cloudwatch/">CloudWatch </a>in particular. I'm assuming that you either have some app running on AWS or at least you know the rudiments on how to launch one.</p>
<h2>I don&rsquo;t need no CloudWatch: my app is bullet-proof</h2>
<p>Yes, you have thought out every contingency, every possible happenstance, and every little accident that the universe could throw at your app. You have plans named after most letters of the alphabet. Your app is so strong that it will outlive cockroaches in case of a nuclear attack. However, there's still that devil-spawn butterfly down there in Brazil, waiting for the TechCrunch feature about your app to go live so it can flap its multicolored wings and bring it to its sorry knees. Or better yet, that butterfly and its buddies are waiting for you to showcase the app to potential investors.</p>
<p>Back in the old days (1990's), the best practices to keep a server up and running included smearing garlic on the sides of the server rack, hanging clovers and horseshoes on the door and lighting a candle to <a href="http://en.wikipedia.org/wiki/Murphy%27s_law">Edward Murphy</a>. This list is not exhaustive. Now, with the advent of cloud computing <a href="http://aws.amazon.com/articles/1697">we don&rsquo;t even know where the servers are</a>, let alone have access to them without getting shot at or eaten by giant Dobermans.</p>
<h2>OK, I need CloudWatch; how do I go about it?</h2>
<p>Out of the box, the guys at AWS give you five metrics at a frequency of one sample every 5 minutes. For free. These metrics are CPU, Disk Reads, Disk Writes, Network In, and Network Out and are stored for two weeks. To have a look, log in to your AWS console and select the EC2 tab. Once you see the instance you're interested in, click on it: on the bottom half of the console, click the tab labeled "Monitoring". Do it, I'll wait here.</p>
<p><span class="full-image-block ssNonEditable"><img src="http://techblog.kontera.com/storage/post-images/basic_monitoring.jpg?__SQUARESPACE_CACHEVERSION=1322732176093" alt="" /></span></p>
<p>While we are on this screen, go to the "Description" tab and write down the instance id; we'll use it later. To get a collective impression of how things are running, select multiple instances on the top half of the console. The "Description" tab will show nothing useful, but the "Monitoring" section will render an aggregation of metrics, each instance with its own color.</p>
<p><span class="full-image-block ssNonEditable"><img src="http://techblog.kontera.com/storage/post-images/multi_monitoring.jpg?__SQUARESPACE_CACHEVERSION=1322732211865" alt="" /></span></p>
<p>There isn&rsquo;t much you can do with these metrics but get a feeling on how your fleet is doing. Think of it as licking your finger to get a sense of where the wind is blowing.</p>
<p>In order to close the feedback loop, we need a way to take action based upon conditions we can measure. Enter <strong>CloudWatch</strong>. On the top of the console, go over the "CloudWatch" tab and select "All Metrics" on the Navigation panel. On the "Viewing" combo box, select "EC2: Instance Metrics". You'll see a list of metrics; we're after the one reading "CPUUtilization" for the MetricName field, and the instance id you wrote down earlier (told you we'll need it) for the InstanceId field. Clicking on it will bring forth a more detailed graph and some nifty buttons on the right side. You can play for a while and go reminiscing with your instance going back and forth in time, up to two weeks ago. The fun part begins with the "Create alert" button.</p>
<p><span class="full-image-block ssNonEditable"><img src="http://techblog.kontera.com/storage/post-images/create_alarm.jpg?__SQUARESPACE_CACHEVERSION=1322732233641" alt="" /></span></p>
<p>In the alarm creation wizard you can set up a threshold condition that will trigger the alarm. Once you set this threshold you can define what you want it to do. Alarms can be in one of <strong>three possible states</strong>: <strong>OK</strong>, <strong>ALARM</strong> and <strong>INSUFFICIENT</strong> <strong>DATA</strong>. When the threshold condition is reached for the period of time set, the alarm will go from <strong>OK</strong> to <strong>ALARM</strong>. This <strong>state transition</strong> could also initiate an <strong>action</strong>. Notice that the actions are performed only during state transitions. Let's have a look at this with an example: say you set an alarm whose threshold is 90% CPU for 30 consecutive minutes. During the first 29 minutes the instance is at 90% CPU the alarm is still in the <strong>OK</strong> state. Worse still, if the CPU is at 100% during those first 29 minutes, the alarm will remain in the <strong>OK</strong> state. Once the alarm transitioned to the <strong>ALARM</strong> state, if an <strong>action</strong> was defined for this transition it will be taken. The alarm will remain in this state until the condition does not hold, i.e. the CPU has been below 90% <em>at least for one sample</em> in the last 30 minutes.</p>
<p>Here's when CloudWatch' sampling frequency becomes relevant: you can have 1 sample every 5 minutes for free, or 1 sample per minute for <a href="http://aws.amazon.com/pricing/cloudwatch/">a monthly fee</a> per instance monitored (at the time of this writing, it was around $3.50/month/instance). If you are sampling once every 5 minutes, and you set the alarm condition for 10 minutes you are actually evaluating only two samples. Conversely, if you take many samples at that rate, things can get very bad till the moment you notice. In short: spend the three fifty and sleep better.</p>
<p>&nbsp;</p>
<div style="background-color: #000000; width: 368px;">
<div style="padding: 4px;"><img id="editor-video-1" src="http://techblog.kontera.com/universal/images/manager/wysiwyg-video.png" alt="" />
<p style="text-align: left; background-color: #ffffff; padding: 4px; margin-top: 4px; margin-bottom: 0px; font-family: Arial, Helvetica, sans-serif; font-size: 12px;"><strong><a href="http://www.southparkstudios.com/full-episodes/s03e03-the-succubus">The Succubus</a></strong><br />Get More: <a style="display: block; position: relative; top: -1.33em; float: right; font-weight: bold; color: #ffcc00; text-decoration: none;" href="http://www.southparkstudios.com/">SOUTH<br />PARK</a><a href="http://www.southparkstudios.com/guide/episodes/s03e03-the-succubus">more...</a></p>
</div>
</div>
<p><span><em>would you rather give 3.50 to the loch ness monster?</em></span></p>
<p>There's also the third state: <strong>INSUFFICIENT DATA</strong>. The alarm enters this state when, as is implied in the state's name, it does not get data from the instance. Setting an action for a transition to this state can be immensely valuable: <em>it basically tells you that your instance is dead</em>.</p>
<p>Regarding the actions that can be taken upon transitions: the most obvious is of course sending an email. To set this up you need to define a channel of sorts in the <a href="http://aws.amazon.com/sns/">Simple Notification Service (SNS)</a> tab. You set a topic ("database-machines") and assign to it subscriptions (email addresses of people on your team). More interesting alternatives to email are HTTP, SMS and SQS. With HTTP you can set up a web service somewhere that reacts to the alert. And with SQS you can dispatch messages through Amazon's Simple Queue Service; how cool is that?</p>
<h2>All that is pretty cool&hellip; what else can CloudWatch do?</h2>
<p>I'll write about custom metrics and auto scaling in the upcoming posts. Stay tuned!</p>
<p>&nbsp;</p>
<p>&nbsp;</p>]]></description><wfw:commentRss>http://techblog.kontera.com/blog/rss-comments-entry-13928399.xml</wfw:commentRss></item><item><title>Mock It All Up</title><category>bdd</category><category>jasmine</category><category>javascript</category><category>tdd</category><dc:creator>Sasha Abramovich</dc:creator><pubDate>Wed, 30 Nov 2011 12:19:00 +0000</pubDate><link>http://techblog.kontera.com/blog/2011/11/30/mock-it-all-up.html</link><guid isPermaLink="false">1083858:12546076:13879525</guid><description><![CDATA[<p>We are supporters of <a href="http://en.wikipedia.org/wiki/Test-driven_development">Test Driven Development</a>&nbsp;/&nbsp;<a href="http://en.wikipedia.org/wiki/Behavior_Driven_Development">Behavior Driven Development</a>, and, consequently, we've picked <a href="http://pivotal.github.com/jasmine/">Jasmine</a> as our ultimate testing tool: it is quick, friendly and easy to learn, and our code is tested with every build.</p>
<p>There are many reasons to write/maintain code in a <a href="http://en.wikipedia.org/wiki/Modular_programming">modular</a> manner. When considering testing, the modular code allows each segment/class/flow to be tested separately. Before you object, let me demonstrate one tip that might come handy. Here is a (simplified) class to be tested:</p>
<pre class="brush: js; toolbar: false; highlight: [5, 6, 7]">    
function ModalOverlay() {
    var shown = false;

    this.show = function() {
        // roughly will open a dialogue only in half of the total requests
        if (Math.random() &lt; 0.5) {
            shown = true;
        }
    }

    this.hide = function() {
        shown = false;
    }

    this.isShown = function() {
        return shown;
    }
}
</pre>
<p>That's right! The overlay code is by no means deterministic but still testable <em>as is</em>. How? Let's inspect the well-known <em><a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Math/random">Math.random()</a></em> method:</p>
<pre class="brush: js; toolbar: false;; highlight: [20,21]">    
describe("Modal Overlay Test", function() {
    var mocRandomObj;
    var modalOverlay;

    function MocRandomObj() {
        var predefinedRandomResult;

        this.set = function(result) {
            predefinedRandomResult = result;
        }
        
        this.get = function() {
            return predefinedRandomResult;
        }
    }

    beforeEach(function() {
        mocRandomObj = new MocRandomObj();

        // here goes the punch!
        spyOn(Math,'random').andCallFake(mocRandomObj.get);

        modalOverlay = new ModalOverlay();
    });

    describe("when probability is coined", function(){
        beforeEach(function() {
            mocRandomObj.set(0.4);
        });

		it("should show overlay", function() {
			modalOverlay.show();
			expect(modalOverlay.isShown()).toBeTruthy();
		});
	});
});
</pre>
<p>As demonstrated above, with a big help from <em><a href="http://pivotal.github.com/jasmine/jsdoc/symbols/jasmine.Spy.html">spyOn()</a></em> a fake code block is called and a known "probabilistic" value is returned. You couldn't ask for it to be any more simple! Generalizing the above approach, we can be extremely flexible and mock all kinds of behaviors in almost every granular level, leaving the tested code intact.</p>
<p>We will be more than happy to hear about your testing/mocking tricks and techniques. If you choose to share any tips or constructive criticism of your own, we are here to listen (and respond).</p>]]></description><wfw:commentRss>http://techblog.kontera.com/blog/rss-comments-entry-13879525.xml</wfw:commentRss></item><item><title>Javascript Functions as a Mind Map</title><category>agile code</category><category>coding</category><category>functional programming</category><category>javascript</category><category>mind map</category><dc:creator>Yehonathan Sharvit</dc:creator><pubDate>Sun, 27 Nov 2011 08:23:47 +0000</pubDate><link>http://techblog.kontera.com/blog/2011/11/27/javascript-functions-as-a-mind-map.html</link><guid isPermaLink="false">1083858:12546076:13879229</guid><description><![CDATA[<html>
<body>
<p>In <a href=http://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882>Clean Code: A Handbook of Agile Software Craftsmanship</a>, the author describes the optimal structure of an agile function:</p>
<p><i>The following advice has appeared in one form or another for 30 years or more.</p>
<ol>
<li>Functions should do one thing.</li>
<li>They should do it well.</li>
<li>They should only do that function. </li>
</ol>
<p>In order to make sure our functions do <b>one thing</b>, we need to make sure that the statements within our function are all at the same level of abstraction.</i></p> 
<p>Usually, the statements are themselves made of functions that also do <b>one thing</b>, leading to a recursive structure. If you think about it, the basic structure of functions is <a href="http://en.wikipedia.org/wiki/Mind_map">Mind Map</a>. We will illustrate this at the end of the article.</p>
<p>Javascript is really one of the best languages to illustrate this Mind Map concepts because in javascript, functions are first class citizens and functions can be nested very naturally. So let's take a very common example in javascript: the testing of some new feature: the feature is only enabled in some predefined ratio of the page views and then we compare performance vs. the old feature. For example, imagine you want to compare the user experience of two designs of the same button. The cool name for this methodology is <a href="http://en.wikipedia.org/wiki/Ab_testing">Ab testing</a>.</p>
<p> As an example, let's dig into the code for the creation of a COOOOL Button: sometimes, we will use the new style and sometimes the old style:</p>
<pre class="brush:js; toolbar:false;">
function createCOOOOLButton(){
    if(shouldUseNewStyle()){
        createNewStyleButton();
    } else {  
        createOldStyleButton(); 
    }
}
</pre>
<p>In this post, we will focus on the implementation of the function <strong>shouldUseNewStyle()</strong>. This function is not the most complex function one has ever written, but it is neither so trivial. There are different constraints to deciding whether we want to use the new/old style: 
<ol>
<li>Ab test value (generated by the server or randomly)</li>
<li>Url parameter (enforce new/old design - mostly used for dev/test phases)</li>
<li>Enforce new design for fancy users</li>
</ol>
<p>Let's try to express this complexity in a single line of code where all the parts belong to the <b>same level of abstraction</b>.</p>
<pre class="brush:js;toolbar:false;">
function shouldUseNewStyle(){
    function isEnforcedByUrlParam() {...}
    function isEnabledByAbTest() {...}
    function isEnforcedByUserCategory(){...}
    return isEnforcedByUserCategory() || isEnforcedByUrlParam() || isEnabledByAbTest();
} 
</pre>
<p>Hey!!! Wait a minute. How do you implement all those functions? The answer is very simple: NEVERMIND. Or more accurately, at the level of abstraction of shouldUseNewStyle, it is of no interest to dig into these details. Writing all those details into separate functions is the essence of the structure of an agile function. It ensures that:
<ol>
<li> The code is structured into small blocks</li>
<li> All parts of the blocks belong to the same level of abstraction </li>
</ol>
Exactly like a Mind Map!!! (Be patient, and wait until you see the illustrating image at the end of this post...)
As a consequence, the code is readable and there is no need to comment it: the code comments itself!</p>
<p> Now, we can continue our recursive journey into the details of the implementation. Let's say, we want to read the code of <b><i>isEnforcedByUrlParam()</i></b>. No problem, just unfold the line (any descent IDE supports folding/unfolding: even vi!!!) and here is the result</p>
<pre class="brush:js;toolbar:false;">
function isEnforcedByUrlParam() {
    function getUrlParameter(variable) {...}
    return getUrlParameter('cool_button_new_style') === '1';
}
</pre>
<p>
It's that simple! The enforcement by url occurs if, and only if, the cool_button_new_style url parameter is switched on. Again very readable. Again, we don't care about the implementation of <b><i>getUrlParameter()</i></b> - at this level of abstraction.
</p>
<p>
Let's end our recursive journey here. Just before you go back home, let me keep my promise and summarize in a single picture the whole structure of the agile function we have described. Let me introduce the Mind Map!!!
</p>
<span class="full-image-block ssNonEditable"><span><img style="width: 1000px;" src="http://techblog.kontera.com/storage/createCOOOOLButton.jpg?__SQUARESPACE_CACHEVERSION=1322746249384" alt=""/></span></span>
</body>
</html>]]></description><wfw:commentRss>http://techblog.kontera.com/blog/rss-comments-entry-13879229.xml</wfw:commentRss></item></channel></rss>
