<?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>Tweetegy</title>
	<atom:link href="http://www.tweetegy.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.tweetegy.com</link>
	<description>Technology, Business, Marketing</description>
	<lastBuildDate>Wed, 25 Apr 2012 09:52:35 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.1</generator>
		<item>
		<title>Forking Ruby Processes or How to fork Ruby</title>
		<link>http://www.tweetegy.com/2012/04/forking-ruby-processes-or-how-to-fork-ruby/</link>
		<comments>http://www.tweetegy.com/2012/04/forking-ruby-processes-or-how-to-fork-ruby/#comments</comments>
		<pubDate>Wed, 25 Apr 2012 09:47:41 +0000</pubDate>
		<dc:creator>Darren</dc:creator>
				<category><![CDATA[Ruby Server Programming]]></category>
		<category><![CDATA[fork]]></category>
		<category><![CDATA[multitask]]></category>
		<category><![CDATA[processes]]></category>
		<category><![CDATA[ruby]]></category>
		<category><![CDATA[threading]]></category>
		<category><![CDATA[threads]]></category>

		<guid isPermaLink="false">http://www.tweetegy.com/?p=701</guid>
		<description><![CDATA[Forking is a UNIX term that makes a process copy itself programmatically. The definition, on good old Wikipedia is: A fork in a multithreading environment means that a thread of execution is duplicated, creating a child thread from the parent thread.. Note this does not necessarily mean that a copy of the memory is allocated. [...]]]></description>
			<content:encoded><![CDATA[<p>Forking is a UNIX term that makes a process copy itself programmatically. The definition, on good old <a href='http://en.wikipedia.org/wiki/Fork_%28operating_system%29'>Wikipedia</a> is: <i>A fork in a multithreading environment means that a thread of execution is duplicated, creating a child thread from the parent thread.</i>. Note this does not necessarily mean that a copy of the memory is allocated. In many cases the memory is shared until one of the processes actually makes a change to something then the memory: this is called copy-on-write (CoW).</p>
<p>So with the UNIX terminology out of the way, how does this work in Ruby? How can we fork a Ruby process using Ruby? Here is a basic example:</p>
<pre class="brush:ruby">
puts "This is the first line before the fork (pid #{Process.pid})"
puts fork
puts "This is the second line after the fork (pid #{Process.pid})"
</pre>
<p>The output from this code might be something like:</p>
<blockquote><p>
This is the first line before the fork (pid 10207)<br />
10209<br />
This is the second line after the fork (pid 10207)<br />
This is the second line after the fork (pid 10209)
</p></blockquote>
<p>So what just happened? Well the first line is pretty clear but then what is the output on the second line (10209)? Well that is the PID returned by the call to fork and , of course, represents the PID of the child process. Then we see the next two lines; one executed by the parent (with PID = 10207) and the other executed by the child (with PID = 10209).</p>
<h2>Blocks</h2>
<p>Very often, the code that developers want to run in a separate process is passed as a block to the fork method, like so:</p>
<pre class="brush:ruby">
puts "You can also put forked code in a block pid: #{Process.pid}"
fork do
  puts "Hello from fork pid: #{Process.pid}"
end
puts "The parent process just skips over it: #{Process.pid}"
</pre>
<p>This outputs the three lines (sometimes) in different order but usally like this:</p>
<blockquote><p>You can also put forked code in a block pid: 10161<br />
The parent process just skips over it: 10161<br />
Hello from fork pid: 10163</p></blockquote>
<p>Note that the PID in the block is different from the PID outside it. This is because the code running within the block is running from within the new process created by using fork.</p>
<h2>Multi-core CPU test</h2>
<p>Let&#8217;s quickly verify one of the main benefits for using fork which is for multi-processing. Let&#8217;s write a test Ruby program that can be used to demonstrate this effect. </p>
<pre class="brush:ruby">
def cpu_intensive_process
  puts "Pid: #{Process.pid}"
  x = 0
  10000000.times do |i|
    x = i + x
  end
end

fork
cpu_intensive_process #should see two processors flat out!
</pre>
<p>When this code is run two processors should max out. If the machine has more than two processors available then <b>only two processors will ever max out</b> with this code as it stands. However, using fork additional times will result in even more processes going flat out (up to all your processors, of course) ! Here is a screen capture of the CPU process monitor on my PC:</p>
<div id="attachment_705" class="wp-caption alignnone" style="width: 710px"><a href="http://www.tweetegy.com/wp-content/uploads/2012/04/Screenshot.png"><img src="http://www.tweetegy.com/wp-content/uploads/2012/04/Screenshot.png" alt="CPU Maxing out during a Ruby Fork" title="CPU Maxing out during a Ruby Fork" width="700" height="235" class="size-full wp-image-705" /></a><p class="wp-caption-text">CPU Maxing out during a Ruby Fork</p></div>
<h2>Memory test</h2>
<p>So what happens with the memory allocation. Apparently in Ruby 1.9.3 (which I am using here) there is no CoW functionality which means that the memory allocation for each process should be the same. Here is a little program that goes some way towards testing that (although, I would say that it is not conclusive):</p>
<pre class="brush:ruby">
hash = Hash.new #load up the memory a little

1000000.times do |i|
  hash[i] = "foo"
end

puts "Hash contains #{hash.keys.count} keys"

def show_memory_usage(whoami)
  pid = Process.pid

  mem = `pmap #{pid}`

  puts "Memory usage for #{whoami} pid: #{pid} is: #{mem.lines.to_a.last}"

  sleep #keep the process alive
end

puts "Now lets fork this process and see what memory is allocated to the child"

puts "Before..."

if fork
  show_memory_usage("parent")
else

  puts "After..."

  1000000.times do |i| #change the values in the child memory allocation
    hash[i] = "bar"
  end

  show_memory_usage("child")
end
</pre>
<p>Here is the result of this test. Feel free to copy this code, changing it around a bit and see what results you get!</p>
<blockquote><p>
Hash contains 1000000 keys<br />
Now lets fork this process and see what memory is allocated to the child<br />
Before&#8230;<br />
After&#8230;<br />
Memory usage for parent pid: 10291 is:  total    62592K<br />
Memory usage for child pid: 10293 is:  total    73164K
</p></blockquote>
<h2>Orphan Processes</h2>
<p>Finally, lets try out testing orphan processes and how they behave. Run this final little program to see:</p>
<pre class="brush:ruby">
fork do
  5.times do
    sleep 1
    puts "I'm an orphan!"
  end
end
abort "Parent process died..."
</pre>
<p>The results are as follows: </p>
<blockquote><p>
Parent process died&#8230;<br />
terminal ~: I&#8217;m an orphan!<br />
I&#8217;m an orphan!<br />
I&#8217;m an orphan!<br />
I&#8217;m an orphan!<br />
I&#8217;m an orphan!
</p></blockquote>
<p>So what&#8217;s happening here? Well the parent process completes and therefore terminates to give me back the terminal prompt. But then suddenly I am interupted with the output of the 5 child processes (now technically orphans) as they execute their code one after the other following a little sleep!</p>
<p>Well that&#8217;s all for my post today on Ruby Forks or how to Fork Ruby. Next time we will be having more fun with Ruby (but not necessary forking it). Till then, happy <i>(insert whatever it is that you do here)</i>!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.tweetegy.com/2012/04/forking-ruby-processes-or-how-to-fork-ruby/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Create reusable UI components and widgets using Backbone.js</title>
		<link>http://www.tweetegy.com/2012/03/create-reusable-ui-components-and-widgets-using-backbone-js/</link>
		<comments>http://www.tweetegy.com/2012/03/create-reusable-ui-components-and-widgets-using-backbone-js/#comments</comments>
		<pubDate>Fri, 30 Mar 2012 07:04:08 +0000</pubDate>
		<dc:creator>Darren</dc:creator>
				<category><![CDATA[Java Script Client Programming]]></category>
		<category><![CDATA[backbone]]></category>
		<category><![CDATA[backbonejs]]></category>
		<category><![CDATA[componentes]]></category>
		<category><![CDATA[frameworks]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[js]]></category>
		<category><![CDATA[ui]]></category>
		<category><![CDATA[uicomponents]]></category>

		<guid isPermaLink="false">http://www.tweetegy.com/?p=690</guid>
		<description><![CDATA[I was building an application in Backbone.js recently and I wanted to experiment with an idea I had to build UI components using Backbone.js. I was given the opportunity when we required a notification element to be displayed on the page. It is possible, to do this in CSS or say using Twitter Bootstrap, however, [...]]]></description>
			<content:encoded><![CDATA[<p>I was building an application in Backbone.js recently and I wanted to experiment with an idea I had to build UI components using Backbone.js. I was given the opportunity when we required a notification element to be displayed on the page. It is possible, to do this in CSS or say using Twitter Bootstrap, however, I wanted to turn this into a basic Backbone.js UI component.</p>
<p>In order to do this we need to think about how the component can be reused in different applications; i.e. not tied directly to any domain specific markup, schema or business logic in the application that is being built. Now, you would probably want to create a separate repository for this project since, after all, it is not strictly meant to live inside an application (unless, of course, your not interested to use the component in any other project other than the one your working on).</p>
<h2>The Template</h2>
<p>The template has a single placeholder <i>message</i> which can be set in the instance of the model that is used in the application. Note, from the line <i>class=&#8221;alert fade in&#8221;</i> that this particular component will work best with <a href="http://twitter.github.com/bootstrap/">Twitter Bootstrap</a>.</p>
<pre class="brush:html">
<script id="notification-template" type="text/template">
<div>
<div id="notification" class="alert fade in">
      <a class="close" data-dismiss="alert" href="#">×</a>
<h3><%= message %></h3>
</div>
</div>

</script>
</pre>
<h2>The Model</h2>
<p>The Notification model has two defaults set: <i>message</i> and <i>status</i> (which is another model). Notice the namespace <i>com.tweetegy.ui</i> used to keep the objects separate from the application.</p>
<pre class="brush:javascript">
com.tweetegy.ui.NotificationModel = Backbone.Model.extend({
    defaults: {
	message: "Loading...",
	status: com.tweetegy.ui.NotificationStatusMessage
    }
});
</pre>
<h2>Notification Status Types</h2>
<p>The Notification Status Types Model acts as an enum holding strings to represent the status of each notification that is shown. This is used to control the style of the notification.</p>
<pre class="brush:javascript">
com.tweetegy.ui.NotificationStatusMessage = "NotificatonStatusMessage";
com.tweetegy.ui.NotificationStatusError = "NotificatonStatusError";
</pre>
<h2>Backbone View</h2>
<p>This is the object that wraps everything up and allows us to reuse this as a component (as we will see later). This is just a standard Backbone View, with an added helper method <i>updateStyleFromStatus</i> which changes the style depending on the status of the Notification and <i>closeNotifcation</i> that hides it.</p>
<p>The other important thing to note is the line <i>this.model.bind(&#8220;change&#8221;, this.render);</i> which is where we use the &#8216;magic&#8217; of Backbone data binding to render our notification anytime the message or status of the applications notification model changes. It means that all we need to do in our application is set either the <i>message</i> or the <i>status</i> and the view will render itself.</p>
<pre class="brush:javascript">
com.tweetegy.ui.NotificationView = Backbone.View.extend({
    className: "well form-inline",

    events: {
	"click .close": "closeNotification"
    },

    initialize: function() {
	_.bindAll(this, 'render', 'updateStyleFromStatus');
	this.template = _.template($('#notification-template').html())
	this.model.bind("change", this.render);
    },

    render: function() {
	var self = this;
	$(this.el).html(this.template(this.model.toJSON()));
	this.updateStyleFromStatus();
	$(this.el).find("#notification").show();
	return this;
    },

    closeNotification: function() {
	$(this.el).find("#notification").hide();
    },

    updateStyleFromStatus: function() {
	var newClass = "alert fade in";
	if (this.model.get('status') == window.NotificationStatusError) {
	    newClass = "alert alert-block alert-error fade in"
	}
	$(this.el).find("#notification").removeClass().addClass(newClass);
    }
});
</pre>
<h2>Using the component</h2>
<p>I used it in an application called &#8220;Front Desk&#8221; and initialized it in the bootstrap.js file during application initialziation:</p>
<pre class="brush:javascript">
    com.tweetegy.FrontDesk.notification = new com.tweetegy.ui.NotificationModel();
    this._notificationView = new com.tweetegy.ui.NotificationView({
	model: y.f.FrontDesk.notification
    });
    $('div#notification').append(this._notificationView.render().el);
</pre>
<p>As mentioned above, in the Backbone View we bind to the models change event to render the view which means all we need to do is change the data in our applications NotificationModel instance (in this case <i>com.tweetegy.FrontDesk.notification</i>) and the Notification will automatically be rendered. Here is an example:</p>
<pre class="brush:javascript">
com.tweetegy.FrontDesk.notification.set({message: "Everything loaded! Starting application..."})
</pre>
<h2>Conclusion</h2>
<p>I have always liked the idea of UI components and using Backbone templates, views and models really makes it easy to build a highly customized UI library for your application, department, company or even to share with the entire community!</p>
<p>I have written another component which uses a Backbone Collection and can be used in a form to collect data from the user. This is a little more complex than the notification example here and I will cover it in a future blog post! Meanwhile, happy coding!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.tweetegy.com/2012/03/create-reusable-ui-components-and-widgets-using-backbone-js/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Ruby Generators</title>
		<link>http://www.tweetegy.com/2012/02/ruby-generators/</link>
		<comments>http://www.tweetegy.com/2012/02/ruby-generators/#comments</comments>
		<pubDate>Thu, 16 Feb 2012 13:22:35 +0000</pubDate>
		<dc:creator>Darren</dc:creator>
				<category><![CDATA[Ruby Server Programming]]></category>
		<category><![CDATA[closures]]></category>
		<category><![CDATA[enumerators]]></category>
		<category><![CDATA[fibonacci]]></category>
		<category><![CDATA[generators]]></category>
		<category><![CDATA[iterators]]></category>
		<category><![CDATA[lambda]]></category>
		<category><![CDATA[ruby]]></category>

		<guid isPermaLink="false">http://www.tweetegy.com/?p=658</guid>
		<description><![CDATA[Simple definition of Generators (Note there is a full definition available on Wikipedia) I think the main thing to take away from the Wikipedia definition is that a generator is something that looks like a function and behaves like an iterator. What this means is that we can create a generator and call it, however [...]]]></description>
			<content:encoded><![CDATA[<h2>Simple definition of Generators</h2>
<p>(Note there is a full definition available on <a href="http://en.wikipedia.org/wiki/Generator_(computer_programming)">Wikipedia</a>)</p>
<p>I think the main thing to take away from the Wikipedia definition is that a generator is something<em> that looks like a function and behaves like an iterator</em>. What this means is that we can create a generator and call it, however many times we want, and it will return the next value in the iteration. It means (as iterators do) that we can have more control over what happens before and after each iteration. </p>
<p>It also means that developers get the additional power to have complete control over what the iterator actually returns (for example a sequence of Prime Numbers). Another benefit is that they require less memory than say iterating over a large array that&#8217;s already explicitly defined.</p>
<h2>So what does a Generator look like in Ruby?</h2>
<p>Since Generators are like Iterators a good example to work with would be to write a program that generates a subset of Prime Numbers or  Fibonacci Numbers &#8211; so this is what we will do in Ruby using a number of different approaches.</p>
<p>In Ruby, Enumerators are a form of Generators so here is a sligtly modified example (to use Ruby 1.9.2 Enumerator class instead of the Ruby 1.8.7 Generator) from <a href="http://anthonylewis.com/2007/11/09/ruby-generators/">Anthony Lewis&#8217;s</a> blog. This example generates a set of Prime Numbers:</p>
<pre class="brush:ruby">
g = Enumerator.new do |g|
  n = 2
  p = []

  while true
    if p.all? { |f| n % f != 0 }
      g.yield n
      p << n
    end
    n += 1
  end
end

p g.take(10) #=> [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
</pre>
<p>Here is another example to generate Fibonacci Numbers that uses the Enumerator class, this is a slightly modified example taken from the <a href='http://ruby-doc.org/core-1.9.3/Enumerator.html#method-c-new'>Ruby docs</a>. The only change I made here is that I am calling <i>yield</i> instead of using the alias <i>&lt;&lt;</i>. You could think of the call to yield or &lt;&lt; as like <i>sending out the value back to the caller</i> (or at least that&#8217;s the way I think of it when I see a <i>yield</i> call in a Generator!)</p>
<pre class="brush:ruby">
fib = Enumerator.new do |y|
  a = b = 1
  loop do
    y.yield a
    a, b = b, a + b
  end
end

p fib.take(10) # => [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
</pre>
<h2>Little more advanced example</h2>
<p>If you want to build your own Generator, using lambdas, check out this example from <a href="http://blog.vmoroz.com/2011/04/ruby-generators.html">Victor Moroz</a></p>
<pre class="brush:ruby">
fib =
  lambda{
    a, b = 0, 1
    lambda{ begin a ensure a, b = b, a + b end }
  }[]

puts (0..19).map{ fib[] }.inspect
</pre>
<h2>Full definitions of Generators</h2>
<p>(Full definition from <a href="http://en.wikipedia.org/wiki/Generator_(computer_programming)">Wikipedia</a>): &#8220;A generator is a special routine that can be used to control the iteration behaviour of a loop. A generator is very similar to a function that returns an array, in that a generator has parameters, can be called, and generates a sequence of values. However, instead of building an array containing all the values and returning them all at once, a generator yields the values one at a time, which requires less memory and allows the caller to get started processing the first few values immediately. In short, a generator <em>looks</em> like a <em>function</em> but behaves like an <em>iterator</em>.&#8221;</p>
]]></content:encoded>
			<wfw:commentRss>http://www.tweetegy.com/2012/02/ruby-generators/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Basic multiple image gallery upload HTML5 and Backbone application</title>
		<link>http://www.tweetegy.com/2012/01/basic-multiple-image-gallery-upload-html5-and-backbone-application/</link>
		<comments>http://www.tweetegy.com/2012/01/basic-multiple-image-gallery-upload-html5-and-backbone-application/#comments</comments>
		<pubDate>Mon, 23 Jan 2012 05:09:39 +0000</pubDate>
		<dc:creator>Darren</dc:creator>
				<category><![CDATA[HTML5 Programming]]></category>
		<category><![CDATA[Java Script Client Programming]]></category>
		<category><![CDATA[Ruby Server Programming]]></category>
		<category><![CDATA[backbone]]></category>
		<category><![CDATA[html5]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[ruby]]></category>
		<category><![CDATA[sinatra]]></category>

		<guid isPermaLink="false">http://www.tweetegy.com/?p=642</guid>
		<description><![CDATA[This is really a very basic example, with the main aim to get anyone started with a simple image upload and persist application using HTML5 and Backbone. This post is essentially a continuation of a previous post where I explained how to preview a local image using HTML5 and Backbone. The main expansion here is [...]]]></description>
			<content:encoded><![CDATA[<p>This is really a very basic example, with the main aim to get anyone started with a simple image upload and persist application using HTML5 and Backbone. This post is essentially a continuation of a previous post where I explained how to <a href='/2012/01/preview-a-local-image-using-backbone-and-html5-javascript/'>preview a local image using HTML5 and Backbone</a>. The main expansion here is that I am adding the capability to:</p>
<ul>
<li>Preview multiple images using a multiple file input</li>
<li>Add all the images to a Backbone collection and persist that collection to a server</li>
</ul>
<h2>Backbone Templates</h2>
<p>I&#8217;ll start with the templates again. In this application I have three templates: one for selecting multiple images, one for displaying a single image preview and a container template for the header text and a placeholder for the collection. </p>
<p>The select multiple images template looks as follows:</p>
<pre class="brush:html">
<script type="text/template" id="gallery-selection-template">
<input id="myGallery" type="file" name="file" multiple />
<button id="saveGallery">Save Gallery</button>
</script>
</pre>
<p>The single image preview template is as follows:</p>
<pre class="brush:html">
<script type="text/template" id="image-template">
<img class="thumb" src='<%= data %>' title='<%= filename %>' />
</script>
</pre>
<p>Finally, the container is the most basic template, since it&#8217;s just a title and a placeholder for the collection:</p>
<pre class="brush:html">
<script type="text/template" id="gallery-template">
<h2>Image Gallery</h2>

<output id="thumbnails"></div>

</script>
</pre>
<p>There is nothing really particullarly special to mention with these templates, so let&#8217;s move on.</p>
<h2>Backbone Views</h2>
<p>I only want to focus on the enhancements I have made which is being able to preview a collection of images and save them to the server via a Backbone collection. Therefore, I will focus on one view here: <em>GalleryView</em>. Actually, this is a standard way of building a view that renders a collection of sub-views in it&#8217;s render method. Here I get a handle on the template <em>gallery-template</em> and append the rendered out <em>ImageView</em> for each Image in the Backbone collection for the Image Gallery:</p>
<pre class="brush:javascript">
 window.GalleryView = Backbone.View.extend({
	template: _.template($("#gallery-template").html()),

	initialize: function() {
	    _.bindAll(this, 'render');
	    this.collection.bind('add', this.render);
	},

	render: function(){
	    var $images,
            collection = this.collection;

            $(this.el).html(this.template({}));
            $images = this.$("#thumbnails");
            this.collection.each(function(image) {
                var view = new ImageView({
                    model: image,
                    collection: collection
                });
                $images.append(view.render().el);
            });

            return this;
	}
});
</pre>
<h2>Backbone Collections</h2>
<p>The Gallery collection is responsible for loading the image data into Backbone Image models and adding them to the collection. There is a function <em>setFromFiles</em> which expects a FileList object passed to it from the multiple file input. Here is the collection code:</p>
<pre class="brush:javascript">
window.Gallery = Backbone.Collection.extend({
	model: Image,
	url: "/images",

	setFromFiles: function(files) {
	    this.reset();
	    self = this;

	    for (var i = 0, f; f = files[i]; i++) {
		var reader = new FileReader();

		reader.onload = (function(theFile, theId) {
		    return function(e) {
			image = new window.Image();
			image.set({id: theId})
			image.set({filename: theFile.name});
			image.set({data: e.target.result});
			self.add(image);
		    };
		})(f);

		reader.readAsDataURL(f,i);
	    }
	}
});
</pre>
<p>The code that calls the <em>setFromFiles</em> method is actually in the <em>ImageSelectionView</em> (that renders the <i>gallery-selection-template</i>) and is called when a change event occurs on the multiple file input. The function looks like this:</p>
<pre class="brush:javascript">
dispatchUpdateGalleryPreview: function(e) {
	this.collection.setFromFiles(e.target.files);
}
</pre>
<p>The <em>e.target.files </em>is the <em>FileList</em> object that the <em>setFromFiles</em> function expects. Note I have prepended the function name with <em>dispatch</em> because it&#8217;s good practice in production code to have the application event driven and therefore this function would actually dispatch a custom event instead of calling the function directly on the collection. </p>
<h2>Backbone Sync</h2>
<p>Finally, we arrive at the persistence part! On the client side we use a little more Backbone. In this case, I simply want to save the entire collection, so I will use <em>Backbone.Sync</em> as follows:</p>
<pre class="brush:javascript">
Backbone.sync("create", this.collection);
</pre>
<p>This will cause Backbone to perform a POST request to the server to the location: &#8216;/images&#8217; which is basically the url set in the Gallery collection earlier. One the server a Ruby file is waiting to process the response. In this example, I am using Sinatra server. Of course, developers are free to use any server technology they want! For completeness, here is the server side Ruby code:</p>
<pre class="brush:ruby">
post "/images" do
  payload = JSON.parse(request.body.read.to_s)

  payload.each do |image|
    data = image["data"]
    i = data.index('base64') + 7
    filedata = data.slice(i, data.length)

    File.open(image["filename"], 'wb') do |f|
      f.write(Base64.decode64(filedata))
    end
  end

end
</pre>
<h2>Conclusion</h2>
<p>This is a very basic application which demonstrates selecting, previewing and saving multiple image files to a Ruby Sinatra endpoint using Backbone and HTML5 on the client. There is no functionality to manage a collection of images, for example, edit or delete. However, I feel this example is enough to get started to build a fuller Image Gallery application! Many features could be implemented in this application including using the HTML5 Canvas to automatically resize images or allow the user to alter the images directly before saving. On the server side, the Ruby script could actually push the images to S3 instead of saving to the file system, for example.</p>
<h2>Code</h2>
<p>The code for this example is <a href='https://bitbucket.org/tweetegy/save_multiple_images_using_backbone/get/107cc356730b.zip'>here</a>.</p>
<h2>Tutorials</h2>
<p><a href='http://www.html5rocks.com/en/tutorials/file/dndfiles/'>Great tutorial using FileReader by HTML5 Rocks</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.tweetegy.com/2012/01/basic-multiple-image-gallery-upload-html5-and-backbone-application/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Save an image file directly to S3 from a web browser using HTML5 and Backbone.js</title>
		<link>http://www.tweetegy.com/2012/01/save-an-image-file-directly-to-s3-from-a-web-browser-using-html5-and-backbone-js/</link>
		<comments>http://www.tweetegy.com/2012/01/save-an-image-file-directly-to-s3-from-a-web-browser-using-html5-and-backbone-js/#comments</comments>
		<pubDate>Thu, 19 Jan 2012 04:45:16 +0000</pubDate>
		<dc:creator>Darren</dc:creator>
				<category><![CDATA[Amazon EC2 S3 Cloud]]></category>
		<category><![CDATA[HTML5 Programming]]></category>
		<category><![CDATA[Java Script Client Programming]]></category>
		<category><![CDATA[api]]></category>
		<category><![CDATA[File]]></category>
		<category><![CDATA[post]]></category>
		<category><![CDATA[rest]]></category>
		<category><![CDATA[s3]]></category>

		<guid isPermaLink="false">http://www.tweetegy.com/?p=543</guid>
		<description><![CDATA[This post continues from the previous post where I show how to preview a local image using Backbone and HTML5 JavaScript. In this post we will actually upload this file directly to an S3 bucket! This post will focus only on that part. Overview The way to avoid any cross-site-scripting restrictions when uploading to S3 [...]]]></description>
			<content:encoded><![CDATA[<p>This post continues from the <a href="/2012/01/preview-a-local-image-using-backbone-and-html5-javascript/">previous post</a> where I show how to <a href="/2012/01/preview-a-local-image-using-backbone-and-html5-javascript/">preview a local image using Backbone and HTML5 JavaScript</a>. In this post we will actually upload this file <strong>directly</strong> to an S3 bucket! This post will focus only on that part.</p>
<h2>Overview</h2>
<p>The way to avoid any cross-site-scripting restrictions when uploading to S3 is essentially to do two things:</p>
<ul>
<li>Use a form to POST the data to S3</li>
<li>Include in that form a Policy and Signature based on the content + your AWS keys</li>
</ul>
<h2>The Form</h2>
<p>Since I am using Backbone.js in this example and since I want to show a preview of the image before uploading it, I realized that I needed to split the form into two templates. The reason was because I needed to be able to refresh the file meta data &#8211; that is essentially the <em>key</em>, <em>policy</em> and <em>signature</em> required by the AWS S3 API. Here are the two templates:</p>
<h4>The Image Meta Template</h4>
<pre class="brush:html">
<script type="text/template" id="image-meta-template">
<input type="hidden" name="key" value='<%= key %>' />
<input type="hidden" name="acl" value='<%= acl %>' />
<input type="hidden" name="Content-Type" value='<%= contentType %>' />
<input type="hidden" name="AWSAccessKeyId" value='<%= AWSAccessKeyId %>' />
<input type="hidden" name="success_action_redirect" value='<%= successActionRedirect %>' />
<input type="hidden" name="x-amz-meta-filename" value='<%=filename %>' />
<input type="hidden" name="Policy" value='<%= POLICY %>' />
<input type="hidden" name="Signature" value='<%= SIGNATURE %>' />
</script>
</pre>
<h4>The Image File Template</h4>
<pre class="brush:html">
<script type="text/template" id="image-file-template">
<form id="formBlob" action='<%= bucket %>.s3.amazonaws.com' method="post" enctype="multipart/form-data" >
<input id="myImage" type="file" name="file" />
<input id="btnSave" type="submit" value="Save Image"></input>
</form>

</script>
</pre>
<p>The data is passed to these templates from the Backbone View. However, when we select a new file we need to first update the preview (this template is discussed in the <a href="/2012/01/preview-a-local-image-using-backbone-and-html5-javascript/">previous post</a>) and then update the image meta template only (not the image file template because that is already correct). So this is the reason I have two templates here.</p>
<p>The interesting attributes of the image meta template are: <em>key</em>, <em>POLICY</em> and <em>SIGNATURE</em> which are all required by the AWS S3 API. The key is the simplest of the three, so let&#8217;s start with that.</p>
<h2>The Key</h2>
<p>The key is simply the bucket key we need to use in order to save (and later retrieve) the image back. In this example, I have the key made up of two attributes on the Backbone Model: folder and filename. The folder is set during the creation of the model in the bootstrap.js file and the filename is set when the user selects a file using the <em>myImage</em> file input. Right after the file has been sucessfully loaded into the preview, I call a function &#8220;updatePoilcy&#8221; which first sets the key attribute on the Model like so:</p>
<pre class="brush:javascript">
updatePolicy: function(){
	var key = this.get('folder') + this.get('filename');
	this.set({key: key});

	//more code later...
}
</pre>
<h2>The Policy</h2>
<p>The Policy is a JSON document that is then converted to Base64 encoding and set as a property on the Model. The code to do this is also in the updatePolicy function (hence the name!). Note that we are getting the data directly from the Model to build this Policy and that it must (and <strong>will</strong>, thanks to Backbone binding!) match with the values in the form template. Here is that code:</p>
<pre class="brush:javascript">
updatePolicy: function(){
//code to set the key attribute on the model

POLICY_JSON = { "expiration": "2012-12-01T12:00:00.000Z",
    "conditions": [
	["eq", "$bucket", this.get('bucket')],
	["starts-with", "$key", this.get('key')],
	{"acl": this.get('acl')},
	{"success_action_redirect": this.get('successActionRedirect')},
	{"x-amz-meta-filename": this.get('filename')},
	["starts-with", "$Content-Type", this.get('contentType')]
    ]
  };

var policyBase64 = Base64.encode(JSON.stringify(POLICY_JSON));
//Set the Policy on the Model so that it is then sent with the Form payload
this.set({POLICY: policyBase64 });

//more code later...
}
</pre>
<h2>The Signature</h2>
<p>The final part of this puzzle is the Signature. This is generated using the Policy and your AWS Secret key and is encrypted using SHA1 like so:</p>
<pre class="brush:javascript">
updatePolicy: function(){
//previous code (shown above)
var secret = this.get('AWSSecretKeyId');
var policyBase64 = Base64.encode(JSON.stringify(POLICY_JSON));
var signature = b64_hmac_sha1(secret, policyBase64);

this.set({SIGNATURE: signature });
}
</pre>
<p>The full <em>updatePolicy</em> function looks like this. Note that this function is called on the Model initialize and on any data changes (i.e. when the user selects a new image).</p>
<pre class="brush:javascript">
updatePolicy: function(){
	    var key = this.get('folder') + this.get('filename');
	    this.set({key: key});

	    POLICY_JSON = { "expiration": "2012-12-01T12:00:00.000Z",
			    "conditions": [
				["eq", "$bucket", this.get('bucket')],
				["starts-with", "$key", this.get('key')],
				{"acl": this.get('acl')},
				{"success_action_redirect": this.get('successActionRedirect')},
				{"x-amz-meta-filename": this.get('filename')},
				["starts-with", "$Content-Type", this.get('contentType')]
			    ]
			  };

	    var secret = this.get('AWSSecretKeyId');
	    var policyBase64 = Base64.encode(JSON.stringify(POLICY_JSON));
	    var signature = b64_hmac_sha1(secret, policyBase64);

	    this.set({POLICY: policyBase64 });
	    this.set({SIGNATURE: signature });
	}
</pre>
<h2>Success Action Redirect</h2>
<p>The <em>successActionRedirect</em> attribute on the model is worth a mention. In this example, I set it to the same page that sent the POST request. If you only want to send data to S3 this is fine, but what if you want to sent some of the meta data to another separate API? There are several ways to do this but one way would be to set this attribute to a service that sends the bucket and key to a backend queue. That queue can be periodically &#8216;popped&#8217; via a cron job that makes a GET request to S3 to retrieve all the meta data saved there for that image file. This data can then be saved to a separate API at this point. This gives the developer full control over where the file meta data is transformed and stored.</p>
<p>Another thing to note is the attribute <em>x-amz-meta-filename</em>. This is actually a custom attribute and the developer can set any number of these with the POST request. They must start with &#8220;x-amz-meta-&#8221; but that&#8217;s about it! So you could have &#8220;x-amz-meta-width&#8221; &#038; &#8220;x-amz-meta-height&#8221; which could be calulated using a HTML5 Canvas set and set as properties on the Model. As long as the Policy and the Form contain these same attributes, they will all be saved along with the image when the form is POST to S3. Very handy!</p>
<h2>Conclusion</h2>
<p>This is a basic example to show how to upload a file directly to S3 from the browser. There are still plenty of unanswered questions such as being able to upload multiple files or upload a file using AJAX and then post some meta data to a separate API (all directly from the browser). These issues can be the subjects of future posts.</p>
<h2>Code</h2>
<p>The code for this example is available <a href='https://bitbucket.org/tweetegy/save-image-directly-s3/get/6fd1c7d713a7.zip'>here</a></p>
<p>To run the example you need to serve the folder from a HTTP server. I usually use Python SimpleHTTPServer for basic examples like this one. Thus, by default, if you CD into the example directory and run <strong>python -m SimpleHTTPServer</strong> then the application will be available at <a href='http://localhost:8000'>http://localhost:8000</a>. You also need to create an S3 account and update <strong>YOUR-BUCKET</strong>, <strong>YOUR-ACCESS-KEY</strong> and <strong>YOUR-SECRET-KEY</strong> in bootstrap.js. Oh! and it will only work in the latest WebKit based browsers. I tested it in Chrome 16.0.912.63 beta. Good luck!</p>
<h2> Tutorials </h2>
<p><a href='http://s3.amazonaws.com/doc/s3-example-code/post/post_sample.html'>POST Example from AWS</a><br />
<a href='http://blog.danguer.com/2011/10/25/upload-s3-files-directly-with-ajax/'>Upload S3 files directly with AJAX</a><br />
<a href='http://docs.amazonwebservices.com/AmazonS3/latest/dev/HTTPPOSTExamples.html'>Another example from AWS</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.tweetegy.com/2012/01/save-an-image-file-directly-to-s3-from-a-web-browser-using-html5-and-backbone-js/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Preview a local image using Backbone and HTML5 JavaScript</title>
		<link>http://www.tweetegy.com/2012/01/preview-a-local-image-using-backbone-and-html5-javascript/</link>
		<comments>http://www.tweetegy.com/2012/01/preview-a-local-image-using-backbone-and-html5-javascript/#comments</comments>
		<pubDate>Wed, 18 Jan 2012 04:31:03 +0000</pubDate>
		<dc:creator>Darren</dc:creator>
				<category><![CDATA[HTML5 Programming]]></category>
		<category><![CDATA[Java Script Client Programming]]></category>
		<category><![CDATA[backbone]]></category>
		<category><![CDATA[File]]></category>
		<category><![CDATA[FileReader]]></category>
		<category><![CDATA[html5]]></category>
		<category><![CDATA[javascript]]></category>

		<guid isPermaLink="false">http://www.tweetegy.com/?p=514</guid>
		<description><![CDATA[HTML5 + Backbone.js make a great partnership! In this blog post, I am going to show how to preview an image in the browser without having to touch the server. I&#8217;ll also use Backbone.js to demonstrate how developers can update a Backbone model with image data and refresh the view to in order to display [...]]]></description>
			<content:encoded><![CDATA[<p>HTML5 + Backbone.js make a great partnership! In this blog post, I am going to show how to preview an image in the browser without having to touch the server. I&#8217;ll also use Backbone.js to demonstrate how developers can update a Backbone model with image data and refresh the view to in order to display a preview of the image.</p>
<h2>Backbone Templates</h2>
<p>Backbone Templates allow developers to build re-usable layouts that can be instansiated within Backbone Views. For this example application, we will need two templates: one for the preview and one for selecting (and later saving) a new image file. Here is the HTML:</p>
<div id="attachment_520" class="wp-caption alignnone" style="width: 610px"><a href="http://www.tweetegy.com/wp-content/uploads/2012/01/preview-image-template.png"><img src="http://www.tweetegy.com/wp-content/uploads/2012/01/preview-image-template.png" alt="Preview Image Template" title="Preview Image Template" width="600" height="122" class="size-full wp-image-520" /></a><p class="wp-caption-text">Preview Image Template</p></div>
<div id="attachment_521" class="wp-caption alignnone" style="width: 610px"><a href="http://www.tweetegy.com/wp-content/uploads/2012/01/select-image-template.png"><img src="http://www.tweetegy.com/wp-content/uploads/2012/01/select-image-template.png" alt="Select Image Template" title="Select Image Template" width="600" height="116" class="size-full wp-image-521" /></a><p class="wp-caption-text">Select Image Template</p></div>
<h2>Backbone Views</h2>
<p>Backbone Views have the responsibility of initializing and rendering the templates into the DOM so that they are visible on the screen. They can also include data from the model. In the templates above, only one requires data from the model; <em>preview-image-template</em>. This is also, in fact, the most basic view in this example, so let&#8217;s look at that first:</p>
<div id="attachment_526" class="wp-caption alignnone" style="width: 610px"><a href="http://www.tweetegy.com/wp-content/uploads/2012/01/preview-image-view.png"><img src="http://www.tweetegy.com/wp-content/uploads/2012/01/preview-image-view.png" alt="Preview Image View" title="Preview Image View" width="600" height="283" class="size-full wp-image-526" /></a><p class="wp-caption-text">Preview Image View</p></div>
<p>I won&#8217;t go into too much detail about what is happening here with the Backbone View but instead I want to focus on the task at hand; to load a preview of the selected image file. The main code to take notice here is the following call to bind in the initialize function:</p>
<pre class="brush:javascript">
this.model.bind('change', this.render);
</pre>
<p>This binds the change event on the model to call the render method on this view. The result will be that whenever <i>any</i> attribute on the model changes, the render method on this view will be called, resulting in the display being updated. But with what? Let&#8217;s continue to build the application with the SelectImageView shown below:</p>
<p><a href="http://www.tweetegy.com/wp-content/uploads/2012/01/select-image-view-e1326714620571.png"><img src="http://www.tweetegy.com/wp-content/uploads/2012/01/select-image-view-e1326714620571.png" alt="" title="select-image-view" width="600" height="512" class="alignnone size-full wp-image-529" /></a></p>
<p>In this View I am binding to some DOM events which I am then passing onto View &#8216;dispatch&#8217; functions. I prepended these functions with &#8216;dispatch&#8217; because in a Production application environment developers would usually trigger custom events which would then be bound by Backbone Models or Views. In this case, I am cheating a little for simplicity and clarity and simply calling the <em>setFromFile</em> function directly on the model. This model, by the way, is exactly the same instance of the model that is bound to the <em>PreviewImageView</em> (see the bootstrap.js file description below to see how developers can set the model attribute on a Backbone View).</p>
<h2>Backbone Models</h2>
<p>This is by far the most interesting part of the application! There is only one model and so this is where we need to define our <em>setFromFile</em> function used in the view earlier. This function will use the new HTML5 FileReader object to read the data from the selected file and update the <i>data</i> attribute on the model with the raw data from the file. As you would have guessed by now, this fires a <em>change</em> event on the model which in turn causes the PreviewImageView to call render and we should see the new image appear on the screen!</p>
<div id="attachment_532" class="wp-caption alignnone" style="width: 619px"><a href="http://www.tweetegy.com/wp-content/uploads/2012/01/my-image-model.png"><img src="http://www.tweetegy.com/wp-content/uploads/2012/01/my-image-model.png" alt="Backbone Model" title="Backbone Model" width="609" height="467" class="size-full wp-image-532" /></a><p class="wp-caption-text">Backbone Model</p></div>
<h2>Backbone Router and bootstrap.js</h2>
<p>For completeness, here is the code for this applications Backbone Router and the bootstrap.js code that kicks everything off. The router does nothing unusual but bootstrap.js deserves a little explanation. </p>
<p>I want the application to load in a state where we see a default image &#8216;preview.png&#8217;. This can be achived by setting the model with default attributes of filename = &#8216;preview.png&#8217; and data = &#8216;img/preview.png&#8217;. This can also be done directly with the model definition too using defaults. Next I create both views and set the model property on each using the same model. As mentioned above, in Production, we would only set the model property on the PreviewImageView and use events to notify of any changes. Finally we create the Backbone Router and start the application!</p>
<p>Here is the code for the Backbone Router and bootstrap.js:</p>
<div id="attachment_534" class="wp-caption alignnone" style="width: 610px"><a href="http://www.tweetegy.com/wp-content/uploads/2012/01/router-e1326715798266.png"><img src="http://www.tweetegy.com/wp-content/uploads/2012/01/router-e1326715798266.png" alt="router" title="router" width="600" height="208" class="size-full wp-image-534" /></a><p class="wp-caption-text">router</p></div>
<div id="attachment_533" class="wp-caption alignnone" style="width: 610px"><a href="http://www.tweetegy.com/wp-content/uploads/2012/01/bootstrap-e1326715782491.png"><img src="http://www.tweetegy.com/wp-content/uploads/2012/01/bootstrap-e1326715782491.png" alt="bootstrap.js file" title="bootstrap.js" width="600" height="309" class="size-full wp-image-533" /></a><p class="wp-caption-text">bootstrap.js file</p></div>
<h2>Some cool tutorials on the subject</h2>
<p><a href='http://www.html5rocks.com/en/tutorials/file/dndfiles/'>HTML5 Rocks</a><br />
<a href='http://backbonetutorials.com/'>Backbone Tutorials</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.tweetegy.com/2012/01/preview-a-local-image-using-backbone-and-html5-javascript/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Ruby blocks, Procs and lambdas</title>
		<link>http://www.tweetegy.com/2012/01/ruby-blocks-procs-and-lambdas/</link>
		<comments>http://www.tweetegy.com/2012/01/ruby-blocks-procs-and-lambdas/#comments</comments>
		<pubDate>Thu, 05 Jan 2012 13:07:10 +0000</pubDate>
		<dc:creator>Darren</dc:creator>
				<category><![CDATA[Ruby Server Programming]]></category>
		<category><![CDATA[closures]]></category>
		<category><![CDATA[lambdas]]></category>
		<category><![CDATA[procs]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[ruby]]></category>

		<guid isPermaLink="false">http://www.tweetegy.com/?p=479</guid>
		<description><![CDATA[Preamble One of my favorite parts of the Ruby Programming language is being able to pass code to a method (usually an iterator) and have that code executed dynamically. In Ruby there are several ways to do this using: blocks, Procs and lamdbas. While these are all very similar, there are some very subtle differences. [...]]]></description>
			<content:encoded><![CDATA[<h2>Preamble</h2>
<p>One of my favorite parts of the Ruby Programming language is being able to pass code to a method (usually an iterator) and have that code executed dynamically. In Ruby there are several ways to do this using: blocks, Procs and lamdbas. While these are all very similar, there are some very subtle differences. First let me explain blocks.</p>
<h2>Blocks</h2>
<p>Blocks are code that can be implicitly passed to a method in Ruby. Any method can in fact be passed a block of code even if the method does not explicitly expect it. In the following example, the method <em>test_blocks</em> does not explicitly expect or do anything with a block, however, if called with a block the code will run printing &#8220;in test_blocks&#8221;</p>
<pre class="brush:ruby">
def test_blocks
  puts "in test_blocks"
end

test_blocks { puts "in the block" }

# Output:
# in test_blocks
</pre>
<p>By simply adding the <em>yield</em> keyword to the method <em>test_blocks</em> the block will then be run causing the output to change:</p>
<pre class="brush:ruby">
def test_blocks
  puts "in test_blocks"
  yield
end

test_blocks { puts "in the block" }

# Output:
# in test_blocks
# in the block
</pre>
<h2>Procs</h2>
<p>It is possible to get a handle on the block by explicitly putting the block as a parameter in the method definition. Note that this must be the last parameter and must start with an ampersand:</p>
<pre class="brush:ruby">
def test_blocks(&#038;block)
  puts block.class
end

test_blocks { puts "in the block" }
# Output:
# Proc
</pre>
<p>Notice that the class is <em>Proc</em> and so the only difference between a block and a Proc is that a Proc can be passed around as an explicit variable. Here is another example where we create a Proc object first and pass that into another method that expects a Proc:</p>
<pre class="brush:ruby">
def test_blocks(some_proc)
  puts some_proc.call
end

some_new_proc = Proc.new { puts "in the Proc !" }
test_blocks(some_new_proc)

# Output:
# in the Proc !
</pre>
<p>The main reason for having both <em>block</em> and <em>Proc</em> is:</p>
<ul>
<li>If we want to write Ruby like syntax when passing code to a method, and we only want to pass a single Proc we use <strong>blocks</strong>. This is very common pattern in Ruby code &#8211; especially with iterators.</li>
<li>If we want to save a piece of code in a variable for reuse then use an explicit <strong>Proc</strong> object</li>
<li>If we want to pass multiple blocks of code to a method and invoke them, we also must use an explicit <strong>Proc</strong> object</li>
</ul>
<h2>Lambda</h2>
<p>Lambda is very similar to a Proc. Let&#8217;s first start off with an example:</p>
<pre class="brush:ruby">
def test_lambda(some_lambda)
  some_lambda.call
end

some_new_lambda = lambda {puts "in the lambda" }
test_lambda (some_new_lambda)

# Output:
# in the Proc !
</pre>
<p>As you can see this looks exactly like the Proc example above, so what is the difference? Well the answer is in the way Ruby handles Procs and Lamdbas. There are, in fact, two differences:</p>
<ol>
<li>Lamdbas check the number of parameters passed into the call, Procs do not check the number of parameters</li>
<li>Lamdbas return from the executing block but <strong>not</strong> from the lexically surrounding method call when they encounter a <em>return</em> keyword (in other words lambda behaves like calling a method which then calls return, whereas a Proc will return from the calling method too</li>
</ol>
<p>Here are a couple of examples to illustrate this. Firstly, the parameter handling differences:</p>
<pre class="brush:ruby">
def test_parameter_handling(code)
  code.call(1,2)
end

l = lambda {|a,b,c| puts "#{a} is a #{a.class}, #{b} is a #{b.class}, #{c} is a #{c.class}" }
p = Proc.new {|a,b,c| puts "#{a} is a #{a.class}, #{b} is a #{b.class}, #{c} is a #{c.class}" }

test_parameter_handling (p)
test_parameter_handling (l)

# Output:
# 1 is a Fixnum, 2 is a Fixnum,  is a NilClass
# ArgumentError: wrong number of arguments (2 for 3)
</pre>
<p>As you can see from the output of the example, the Proc does not care if we only call with two parameters when it&#8217;s possible to use three parameters &#8211; it simply sets all unused parameters to <em>nil</em>. However, when passing a <em>lambda</em> to the method, Ruby throws an <em>ArgumentError</em> instead. So if you want your Proc (a lamdba is an instance of Proc, by the way) to be called with a specific set of parameters &#8211; no more and no less &#8211; then use <em>lamdba</em>.</p>
<p>Here is an example that demonstrates the differences how Proc and lamdba behave when they encounter a <em>return</em> statement:</p>
<pre class="brush:ruby">
def return_using_proc
  Proc.new { return "Hi from proc!"}.call
  puts "end of proc call"
end

def return_using_lambda
  lambda {return "Hi from lambda!"}.call
  puts "end of lambda call"
end

puts return_using_proc
puts 

# Output
# Hi from proc!
# end of lambda call
</pre>
<p>When <em>return_using_proc</em> is called the method stops processing as soon as it encounters the return statement and we see &#8220;Hi from proc!&#8221; output. When <em>return_using_lambda</em> is called the return is encountered but does not cause the method to return and instead the method continues to run so we see &#8220;end of lambda call&#8221; output.</p>
<p>Here is another example to demonstrate this in a slightly different way:</p>
<pre class="brush:ruby">
def test_returns
  puts "top"

  pr = Proc.new { return }
  pr.call

  puts "bottom"
end

puts "before call"
test_returns
puts "after call"

# Output
# before call
# top
# after call
</pre>
<p>In this example, we see &#8216;before call&#8217; output followed by &#8216;top&#8217; as we would expect but then we see &#8216;after call&#8217; &#8211; note there is no output for our puts &#8216;bottom&#8217; statement. This is because the call to the Proc object (pr.call) caused the calling method to return since the Proc contained a return statement. If we replace the Proc with a lambda then we would see &#8216;bottom&#8217; output as well since the call to the lambda simply returns back to the method which called it.</p>
<p>The main reason for this diffence is because Procs are more like blocks of code that can be &#8216;dropped in&#8217; and executed whereas lamdbas behave more like methods. It is also for this reason why lambdas are more strict with parameter checking &#8211; just as methods are.</p>
<h2>Ruby Closures</h2>
<p>It&#8217;s important to note that blocks, Procs and lambdas are all <a href='http://en.wikipedia.org/wiki/Closure_%28computer_science%29'>closures</a>. Basically this means that they hold the values of any variables that were around when they were created. This is a very powerful feature of Ruby because if we wrap creating a block of code in a method call we can dynamically create different behavior. For example:</p>
<pre class="brush:ruby">
def create_multiplier(m)
  lambda {|val| val * m}
end

two_times = create_multiplier(2)
three_times = create_multiplier(3)

puts two_times.call(1)
puts three_times.call(1)

# Output
# 2
# 3
</pre>
<h2>Conclusion</h2>
<p>In conclusion we are dealing with blocks of code that can be passed to method calls and executed within that method. When the block of code is executed in the method the state of any variables at the time of creation of that block of code are used. This means that blocks, Procs and lamdbas are all <a href='http://en.wikipedia.org/wiki/Closure_%28computer_science%29'>closures</a> in Ruby.</p>
<p>It&#8217;s also interesting to conclude that:</p>
<p><strong>Lambdas</strong> have <strong>strict</strong> parameter checking and <strong>diminutive</strong> returns.<br />
<strong>Procs</strong> have <strong>no</strong> parameter checking and <strong>strong</strong> returns.<br />
<strong>Blocks</strong> and <strong>lambdas</strong> are essentially just anonymous <i>Procs</i></p>
<h2>Some tutorials</h2>
<ul>
<li><a href='http://www.robertsosinski.com/2008/12/21/understanding-ruby-blocks-procs-and-lambdas/'>Understanding Ruby Blocks, Procs and Lambdas</a></li>
<li><a href='http://pragprog.com/screencasts/v-dtrubyom/the-ruby-object-model-and-metaprogramming'>The Ruby Object Model and Metaprogramming &#8211; Episode 3</a>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.tweetegy.com/2012/01/ruby-blocks-procs-and-lambdas/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Getting started with the HTML5 Geolocation API</title>
		<link>http://www.tweetegy.com/2011/12/getting-started-with-the-html5-geolocation-api/</link>
		<comments>http://www.tweetegy.com/2011/12/getting-started-with-the-html5-geolocation-api/#comments</comments>
		<pubDate>Thu, 22 Dec 2011 05:24:32 +0000</pubDate>
		<dc:creator>Darren</dc:creator>
				<category><![CDATA[HTML5 Programming]]></category>
		<category><![CDATA[api]]></category>
		<category><![CDATA[geolocation]]></category>
		<category><![CDATA[html5]]></category>

		<guid isPermaLink="false">http://www.tweetegy.com/?p=454</guid>
		<description><![CDATA[Geolocation presents major opportunities for mobile application development. It&#8217;s an exciting way to work with location based applications and services and really give the user something that is of great value to them. By using Geolocation, developers can find out the location of the user, can give the user directions to other places, can tell [...]]]></description>
			<content:encoded><![CDATA[<p>Geolocation presents major opportunities for mobile application development. It&#8217;s an exciting way to work with location based applications and services and really give the user something that is of great value to them. By using Geolocation, developers can find out the location of the user, can give the user directions to other places, can tell the user where the nearest XYZ place might be, can tell the user how far they have moved in a given timeframe and more, and more&#8230;</p>
<h2>The Basics</h2>
<p>When using the Geolocation API it is important to know the data that we are working with. With Geolocation we work with Latitude and Longitude values. These represent the following:</p>
<ul>
<li><b>Latitude</b>: The distance North or South of the equator</li>
<li><b>Longitude</b>: The distance East or West of Greenwich, England</li>
</ul>
<p>Usually, these values come from the mobile device GPS or, if the GPS is not available then the co-ordinates can be inferred from the IP address, Wi-Fi or even entered directly by the user.</p>
<h2>Privacy</h2>
<p>Since we are dealing with sensitive information, there are strict privacy requirements that must be followed when working with the Geolocation API. Fortunately, privacy user confirmation is triggered in all browses (that support Geolocation) automatically on any API call. You may have seen the message in some applications asking if it is ok that the application uses your location. This is Geolocation API security kicking in! It happens only once per domain so once you accept you will not need to accept every time you perform a Geolocation based action on that site.</p>
<h2>Getting the co-ordinate data</h2>
<p>To get the current position of the user, simply execute this function. Note that <em>updateLocation</em> is a callback function to handle the result.</p>
<pre class="brush:javascript">
navigator.geolocation.getCurrentPosition(updateLocation)
</pre>
<p>The position object passed to the <em>updateLocation()</em> function contains the following data attributes:</p>
<ul>
<li>latitude</li>
<li>longitude</li>
<li>accuracy</li>
</ul>
<p>Here is an example of how the updateLocation function might appear:</p>
<pre class="brush:javascript">
function updateLocation(position) {
    var latitude = position.coords.latitude;
    var longitude = position.coords.longitude;
    var accuracy = position.coords.accuracy;
    var timestamp = position.timestamp;
    document.getElementById("latitude").innerHTML = latitude;
    document.getElementById("longitude").innerHTML = longitude;
    document.getElementById("accuracy").innerHTML = accuracy;
    document.getElementById("timestamp").innerHTML = timestamp;
}
</pre>
<h2>Handling Errors</h2>
<p>It&#8217;s important to handle errors in Geolocation API calls because there is so much potential for things to go wrong: network error, GPS issues, privacy / security issues, timeout etc. We can handle errors using another callback function that takes an error code and deals with that code accordingly. What we need to do first is include that callback function in the call to the <em>getCurrentPosition</em> Geolocation function:</p>
<pre class="brush:javascript">
navigator.geolocation.getCurrentPosition(updateLocation, handleError)
</pre>
<p>Then our <em>handleError</em> callback function might look like this (notice the 4 possible error codes):</p>
<pre class="brush:javascript">
function handleError(error) {
    switch (error.code) {
    case 0:
	updateStatus("There was an error while retrieving your location: " + error.message);
	break;
    case 1:
	updateStatus("The user prevented this page from retrieving a location.");
	break;
    case 2:
	updateStatus("The browser was unable to determine your location: " + error.message);
	break;
    case 3:
	updateStatus("The browser timed out before retrieving the location.");
	break;
    }
}
</pre>
<h2>Repeated requests to keep track of users position</h2>
<p>In the example above, <i>getCurrentPosition() </i>makes one call to get the users location. However, there maybe situations where you will want to track the users <em>change</em> in position over time. In this case it is better to use <i>watchPosition()</i>. </p>
<p>Fortunately, it&#8217;s really simple to change to use watchPosition, here is an example so you can see how similar it is. Note we can set the <em>watchId</em> variable so that we can tell the API to &#8216;stop watching &#8216; by making a call to <i>clearWatch</i> function at a later time:</p>
<pre class="brush:javascript">
var watchId = navigator.geolocation.watchPosition(updateLocation, handleError);
//Do something and sometime later we can stop watching by passing the watchId to clearWatch():
navigator.geolocation.clearWatch(watchId);
</pre>
<h2>Conclusion</h2>
<p>While this was a very basic introduction to the HTML5 Geolocation API, it is enough for developers to get started building something useful! Remember that you can also use Google Maps API to integrate mapping data into your application too!</p>
<h2>Some cool examples</h2>
<ul>
<li><a href="http://merged.ca/iphone/html5-geolocation">Basic Example</a></li>
<li><a href="http://www.ip2location.com/html5geolocationapi.aspx">Demo&#8217;s difference with IP and Geolocation API based calls</a></li>
</ul>
<h2>Some tutorials</h2>
<ul>
<li><a href="http://mobile.tutsplus.com/tutorials/mobile-web-apps/html5-geolocation/">Basic Tutorial</a></li>
<li><a href="http://developer.practicalecommerce.com/articles/2066-An-Introduction-to-HTML5-Geolocation">Introduction Tutorial</a></li>
<li><a href="http://www.netmagazine.com/tutorials/link-users-geolocation-data-html5">More detailed tutorial</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.tweetegy.com/2011/12/getting-started-with-the-html5-geolocation-api/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Connecting a HTML5 application to a MongoDB instance via MongoLab REST API</title>
		<link>http://www.tweetegy.com/2011/12/connecting-a-html5-application-to-a-mongodb-instance-via-mongolab-rest-api/</link>
		<comments>http://www.tweetegy.com/2011/12/connecting-a-html5-application-to-a-mongodb-instance-via-mongolab-rest-api/#comments</comments>
		<pubDate>Sat, 10 Dec 2011 07:59:58 +0000</pubDate>
		<dc:creator>Darren</dc:creator>
				<category><![CDATA[HTML5 Programming]]></category>
		<category><![CDATA[Java Script Client Programming]]></category>
		<category><![CDATA[nosql]]></category>
		<category><![CDATA[REST Programming]]></category>
		<category><![CDATA[api]]></category>
		<category><![CDATA[html5]]></category>
		<category><![CDATA[mongodb]]></category>
		<category><![CDATA[mongolabs]]></category>
		<category><![CDATA[rest]]></category>

		<guid isPermaLink="false">http://www.tweetegy.com/?p=427</guid>
		<description><![CDATA[Overview I needed a free, document based, online data store so that I could quickly build a HTML5 prototype. As an exercise, I quickly whipped up a simple application that can store basic contact details of people. Getting Started with MongoLab To get started with MongoLab is really easy. Simply create your account, your database [...]]]></description>
			<content:encoded><![CDATA[<h2>Overview</h2>
<p>I needed a free, document based, online data store so that I could quickly build a HTML5 prototype. As an exercise, I quickly whipped up a simple application that can store basic contact details of people.</p>
<h2>Getting Started with MongoLab</h2>
<p>To get started with MongoLab is really easy. Simply create your account, your database and your first collection and your good to go. The only reference document you need for this exercise is the <a href='http://support.mongolab.com/entries/20433053-rest-api-for-mongodb'>MongoLab REST API docs</a></p>
<h2>First things first: Adding data to your MongoDB using REST</h2>
<p>I am only going to show you the absolute basics here, so no security, validation, callbacks or fancy UI designs &#8211; just the basics! I built this by creating a simple HTML5 form and I used XMLHttpRequest API to send the data to MongoLab. </p>
<p>Here are the code snippets, first the HTML:</p>
<pre class="brush:html">
<form id="myform" name="myform">
<input id="name" type="text" name="name" placeholder="Name" ><br/>
<input id="email" type="email" name="email" placeholder="Email" ><br/>
<input type="button" onclick="send(this.form);" value="Save">
</form>
</pre>
<p>&#8230;and the JavaScript. Note the variable <i>json</i> which is not defined in this snippet but is basically a JSON representation of the form data. The easiest way to get your form data into JSON is to use JQuery (again, I am not including how to do that to keep us focused on how to interact with the MongoLab RESTful API). Note: you will need to replace YOUR-DATABASE, YOUR-COLLECTION and YOUR-API-KEY with your values.</p>
<pre class="brush:javascript">
    var xhr = new XMLHttpRequest();
    xhr.open("POST", "https://api.mongolab.com/api/1/databases/YOUR-DATABASE/collections/YOUR-COLLECTION?apiKey=YOUR-API-KEY", true);
    xhr.setRequestHeader("Content-Type", "application/json");
    xhr.send(json);
</pre>
<p>When you load your page you will be able to add a new record to the database. You can check that it has arrived at the database by logging into mongolab.com and viewing the collection.</p>
<h2>Next up: Display a collection of items</h2>
<p>It&#8217;s really easy to get data from the MongoLab API &#8211; a simple GET request will do, in fact! Apart from that, this step is really an exercise in using the JavaScript DOM (which I will not cover here). Here is the HTML &#8211; as you can see it is just a placeholder for the data. I am using UL but, of course, you can load the data into whatever placeholder you like. </p>
<pre class="brush:html">
<ul id="result">
</ul>
</pre>
<p>Basic JavaScript snippet shown below. As you see just a simple GET request (and send null since there is no payload). To complete this you&#8217;ll want to add an <i>onreadystatechange</i> function to detect when the request.status is 200 and then call your DOM rendering function at that point.</p>
<pre class="brush:javascript">
    var request = new XMLHttpRequest();
    request.open("GET", "https://api.mongolab.com/api/1/databases/YOUR-DATABASE/collections/YOUR-COLLECTION?apiKey=YOUR-API-KEY");
    request.send(null);
</pre>
<h2>View a single document</h2>
<p>To render a single document in your HTML5 application, you&#8217;ll want to, again, use the GET request but this time passing in the document id in the query string and using that to pull the correct document from your MongoDB. The HTML snippet is the same as for the collection, so I&#8217;ll just show the JavaScript code below. Notice how to get the id from the query string. This exampled is hard coded, and thus assumes the id is first in the query string and is in the form &#8220;id=12345&#8243;.</p>
<pre class="brush:javascript">
    var queryString = window.top.location.search.substring(1);
    id = queryString.substring(3,queryString.length);
    var request = new XMLHttpRequest();
    request.open("GET", "https://api.mongolab.com/api/1/databases/YOUR-DATABASE/collections/YOUR-COLLECTION/" + id + "?apiKey=YOUR-API-KEY");
    request.send(null);
</pre>
<h2>Edit a document</h2>
<p>Since this is a RESTful API, to update a document we need to use a PUT verb. The HTML snippet is almost the same as the adding data example, so just the JavaScript snippet here. Notice the getId() function call which simply gets the id from the query string. Obviously this is not a production ready or secure way of getting the id for a document we want to update.</p>
<pre class="brush:javascript">
    var xhr = new XMLHttpRequest();
    xhr.open("PUT", "https://api.mongolab.com/api/1/databases/YOUR-DATABASE/collections/YOUR-COLLECTION/" + getId() + "?apiKey=YOUR-API-KEY", true);
    xhr.setRequestHeader("Content-Type", "application/json");
    xhr.send(json);
</pre>
<h2>Delete a document</h2>
<p>Finally, we want to be able to delete a document. This is really easy as shown. Notice you need to send <i>null</i> like before because there is no payload.</p>
<pre class="brush:javascript">
    var request = new XMLHttpRequest();
    request.open("DELETE", "https://api.mongolab.com/api/1/databases/YOUR-DATABASE/collections/YOUR-COLLECTION/" + id + "?apiKey=YOUR-API-KEY");
    request.send(null);
</pre>
<h2>Conclusion</h2>
<p>Thankfully, with the excellent service provided by MongoLab.com developers are able to build nosql document database driven applications in no time and at no cost!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.tweetegy.com/2011/12/connecting-a-html5-application-to-a-mongodb-instance-via-mongolab-rest-api/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Getting started with the HTML5 Audio Video API</title>
		<link>http://www.tweetegy.com/2011/11/getting-started-with-the-html5-audio-video-api/</link>
		<comments>http://www.tweetegy.com/2011/11/getting-started-with-the-html5-audio-video-api/#comments</comments>
		<pubDate>Sat, 12 Nov 2011 07:05:48 +0000</pubDate>
		<dc:creator>Darren</dc:creator>
				<category><![CDATA[HTML5 Programming]]></category>
		<category><![CDATA[api]]></category>
		<category><![CDATA[audio]]></category>
		<category><![CDATA[html5]]></category>
		<category><![CDATA[video]]></category>

		<guid isPermaLink="false">http://www.tweetegy.com/?p=397</guid>
		<description><![CDATA[The HTML5 Audio and Video API is a real game changer. For starters, think about how this affects the (once) mighty Flash. For years Flash was the most popular way to distribute audio and especially video via the web to a browser. Now that can change with HTML5. Even Adobe has announced that it is [...]]]></description>
			<content:encoded><![CDATA[<p>The HTML5 Audio and Video API is a real game changer. For starters, think about how this affects the (once) mighty Flash. For years Flash was the most popular way to distribute audio and especially video via the web to a browser. Now that can change with HTML5. Even Adobe has announced that it is <a href='http://searchenginewatch.com/article/2124277/Adobe-To-Stop-Developing-Flash-For-Mobile'>to stop developing Flash for mobile</a></p>
<h2>The Basics</h2>
<p>Getting started with the Audio and Video API is real easy (as is everything in HTML5, in fact!). At the very basic level all you need to do is declare an &lt;audio&gt; or &lt;video&gt; tag in your html like so:</p>
<pre class="brush:html">
<video src="media/some-video-file.mp4" />
</pre>
<p>This is so basic that it does not even render the controls. In order to control video playback, the user has to use the context menu (which is not so easy to find for some). In order to render controls simply add the controls attribute like so:</p>
<pre class="brush:html">
<video src="media/some-video-file.mp4" controls />
</pre>
<p>Now we see the controls appear as sown below (notice that the first frame of the video is shown by default):</p>
<div id="attachment_403" class="wp-caption alignnone" style="width: 310px"><a href="http://www.tweetegy.com/wp-content/uploads/2011/11/html5-video-with-controls.jpg"><img src="http://www.tweetegy.com/wp-content/uploads/2011/11/html5-video-with-controls-300x226.jpg" alt="HTML5 Video with controls" title="HTML5 Video with controls" width="300" height="226" class="size-medium wp-image-403" /></a><p class="wp-caption-text">HTML5 Video with controls</p></div>
<p>Simple! So why does HTML5 have the option to not show the controls? Well the reason is to give the developer control over how the controls are rendered. Since JavaScript has an API to access the Audio and Video instances within the browser it is possible to create and style a &#8220;Play/Pause&#8221; button in anyway you like! Here is some example JavaScript code that demonstrates how to do this:</p>
<pre class="brush:javascript">
function playPauseMusic() {
      var music = document.getElementById("music");
      var playPauseBtn = document.getElementById("playPauseBtn");
      if (music.paused) {
        music.play();
        playPauseBtn.innerHTML = "Pause the Music!";
      }
      else {
        music.pause();
        playPauseBtn.innerHTML ="Play the Music!";
      }
    }
</pre>
<p>As you can see this is quite easy to do. Simply add an audio tag to the html page with id=&#8221;music&#8221; and a button tag with id=&#8221;playPauseBtn&#8221; and this JavaScript can be used to control the play / pause of your  music! All it does is render a button but it works and demonstrates how easy it is to use the (in this case) Audio API (the Video API is very similar, by the way).</p>
<h2>Use the Source!</h2>
<p>So far I have only shown some simple examples. It is possible in HTML5 to specify different sources so that you can provide different file types for the media you want rendered. So in order to increase the chance that the browser supports the particular container or codec, make sure you save your media as different file types (e.g. ogg, mp4 etc) and use the source as in the following audio example:</p>
<pre class="brush:html">
<audio>
  <source src="1.ogg" >
  <source src="1.mp3" >
  Some music by someone!
</audio>
</pre>
<p>Note the text &#8216;Some music by someone!&#8217; just before the closing &lt;audio&gt; tag. This text will be rendered in non-supporting browsers so it provides a nice and easy way to gracefully fallback if that is the case.</p>
<h2>Autoplay attribute</h2>
<p>HTML5 Audio and Video API comes with the optional autoplay attribute. Use this with caution! There is nothing more annoying than a website that starts playing audio or video automatically on load! However, if you must, simply include the attribute in the &lt;audio&gt; or &lt;video&gt; tag.</p>
<h2>Video API Basic Tip: Play Video on Mouseover</h2>
<p>One thing you might have seen on the web is the concept of playing a video in a thumbnail when the mouse hovers over the video image. This is surprisingly easy to do in HTML5, by the way! All you need to do is set the onmouseover and onmouseout events to call play() and pause() methods respectively, like so:</p>
<pre class="brush:html">
<video id="movies" onmouseover="this.play()" onmouseout="this.pause()" autobuffer="true">
<!-- video source here -->
</video>
</pre>
<p>That&#8217;s it for this very basic introduction! If you want to learn more about the HTML5 Audio and Video API, check out some of the following resources:</p>
<h2>Some cool examples</h2>
<ul>
<li><a href='http://shapeshed.com/examples/HTML5-video-element/'>Basic Examples</a></li>
<li><a href='http://double.co.nz/video_test/events.html'>Video Events Example</a></li>
<li><a href='http://www.808.dk/?code-html-5-video'>Some notes on HTML5 Video Codes support</a></li>
</ul>
<h2>Some tutorials</h2>
<ul>
<li><a href='https://developer.mozilla.org/en/Using_audio_and_video_in_Firefox'>A great HTML5 Audio Video API tutorial by Mozilla</a></li>
<li><a href='http://www.html5rocks.com/en/tutorials/video/basics/'>Another great tutorial, this time from HTML5 Rocks!</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.tweetegy.com/2011/11/getting-started-with-the-html5-audio-video-api/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

