<?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>Merbist &#187; Tutorial</title>
	<atom:link href="http://merbist.com/category/tutorial/feed/" rel="self" type="application/rss+xml" />
	<link>http://merbist.com</link>
	<description>Random thoughts of a software developer</description>
	<lastBuildDate>Tue, 03 Jan 2012 02:34:07 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3</generator>
<xhtml:meta xmlns:xhtml="http://www.w3.org/1999/xhtml" name="robots" content="noindex" />
		<item>
		<title>My RubyConf 2011 talk is online</title>
		<link>http://merbist.com/2011/12/09/my-rubyconf-2011-talk-is-online/</link>
		<comments>http://merbist.com/2011/12/09/my-rubyconf-2011-talk-is-online/#comments</comments>
		<pubDate>Fri, 09 Dec 2011 14:47:59 +0000</pubDate>
		<dc:creator>Matt Aimonetti</dc:creator>
				<category><![CDATA[ruby]]></category>
		<category><![CDATA[Tutorial]]></category>
		<category><![CDATA[concurrency]]></category>
		<category><![CDATA[garbage collector]]></category>
		<category><![CDATA[gil]]></category>

		<guid isPermaLink="false">http://merbist.com/?p=1203</guid>
		<description><![CDATA[I realize I forgot to mention that my RubyConf talk is now online on the confreaks site (wait until the end, Matz actually answers a question from the audience). I wrote a couple follow up posts you might also be interested in: About concurrency and the GIL Data safety and GIL removal]]></description>
			<content:encoded><![CDATA[<p>I realize I forgot to mention that my RubyConf talk is now online on the <a href="http://confreaks.net/videos/714-rubyconf2011-complex-ruby-concepts-dummified">confreaks site</a> (wait until the end, Matz actually answers a question from the audience).</p>
<p><img class="aligncenter" src="https://img.skitch.com/20111209-pdfksgd2sufg8ywrpnjd4dnru4.jpg" alt="Photo of Matt Aimonetti giving a talk at RubyConf 2011 with one of his slides showing how thread scheduling works" width="653" height="422" /></p>
<p>I wrote a couple follow up posts you might also be interested in:</p>
<ul>
<li><a title="About concurrency and the GIL" href="http://merbist.com/2011/10/03/about-concurrency-and-the-gil/">About concurrency and the GIL</a></li>
<li><a title="Data safety and GIL removal" href="http://merbist.com/2011/10/18/data-safety-and-gil-removal/">Data safety and GIL removal</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://merbist.com/2011/12/09/my-rubyconf-2011-talk-is-online/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Go&#8217;s reflection example</title>
		<link>http://merbist.com/2011/06/27/golang-reflection-exampl/</link>
		<comments>http://merbist.com/2011/06/27/golang-reflection-exampl/#comments</comments>
		<pubDate>Mon, 27 Jun 2011 20:12:32 +0000</pubDate>
		<dc:creator>Matt Aimonetti</dc:creator>
				<category><![CDATA[Misc]]></category>
		<category><![CDATA[Tutorial]]></category>

		<guid isPermaLink="false">http://merbist.com/?p=1084</guid>
		<description><![CDATA[The Go Programming language is really cool language by Google. According to the sales pitch, it&#8217;s a &#8220;fast, statically typed, compiled language that feels like a dynamically typed, interpreted language&#8221;. Well, if you are like me, you don&#8217;t trust sales pitches because you know that people writing them dont&#8217; care about you, they care about [...]]]></description>
			<content:encoded><![CDATA[<p>The <a title="Go Lang" href="http://golang.org/" target="_blank">Go Programming language</a> is really cool language by Google. According to the sales pitch, it&#8217;s a <strong><em>&#8220;fast, statically typed, compiled language that feels like a dynamically typed, interpreted language&#8221;</em></strong>. Well, if you are like me, you don&#8217;t trust sales pitches because you know that people writing them dont&#8217; care about you, they care about their product. However cynical you are, you still have to check the facts. So here is a quick demonstration showing how to use Go&#8217;s reflection feature.</p>
<p>Installing Go is actually really straight forward on a Mac, and slightly harder on Linux, check <a title="golang install" href="http://golang.org/doc/install.html" target="_blank">this guide </a>to see how to build Go in a few minutes.</p>
<p>Once all setup, you might want to read the documentation to see how to code in Go. Go is actually a kind of nice version of C with a<a title="Golang specs" href="http://golang.org/doc/go_spec.html" target="_blank"> simplified syntax</a>, no header files, really fast compilation time, a garbage collector and a <a title="golang types and interfaces" href="http://golang.org/doc/effective_go.html?#interfaces_and_types" target="_blank">simple way to approach object inheritance</a> without turning in the complicated mess C++ is. The language is designed around the concept of <a title="Golang concurrency" href="http://golang.org/doc/effective_go.html?h=goroutines#concurrency" target="_blank">goroutines, a very nice way to handle concurrency</a>. It also has some features that Rubyists, Pythonistas and Javascripters wouldn&#8217;t want to live without such as closures and some they probably wish they had such as <a title="Go Defer" href="http://golang.org/doc/effective_go.html?#defer" target="_blank">defer</a>. But of the things we are used to with dynamic languages is the concept of reflection. In a nutshell, at runtime, your code can reflect on the type of a given object and let the developer act accordingly. Depending on your programming background that might be obvious or you might not see the value. To be honest, that&#8217;s not the question here. What I&#8217;m interested in showing you is how it works.</p>
<p>For the sake of this demo, let&#8217;s pretend we want to have a &#8220;Dish&#8221; data model, each instance of the &#8220;Dish&#8221; type will have a few attributes, an id, a name, an origin and a custom query which really is a function that we store as an attribute. Here is how we would represent that model in Go:</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">// Data Model</span>
type Dish <span style="color: #993333;">struct</span> <span style="color: #009900;">&#123;</span>
  Id  <span style="color: #993333;">int</span>
  Name string
  Origin string
  Query func<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>This is more or less the equivalent of the following Ruby code:</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;"><span style="color:#9966CC; font-weight:bold;">class</span> Dish
  attr_accessor <span style="color:#ff3333; font-weight:bold;">:id</span>, <span style="color:#ff3333; font-weight:bold;">:name</span>, <span style="color:#ff3333; font-weight:bold;">:origin</span>, <span style="color:#ff3333; font-weight:bold;">:query</span>
<span style="color:#9966CC; font-weight:bold;">end</span></pre></div></div>

<p>Ruby works slightly differently in the sense that defining attribute accessors create getters and setter methods but doesn&#8217;t technically create instance variables until they are used. Here is what I mean:</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;">shabushabu = Dish.<span style="color:#9900CC;">new</span>
shabushabu.<span style="color:#9900CC;">instance_variables</span> <span style="color:#008000; font-style:italic;"># =&gt; []</span>
shabushabu.<span style="color:#9900CC;">name</span> = <span style="color:#996600;">&quot;Shabu-Shabu&quot;</span>
shabushabu.<span style="color:#9900CC;">instance_variables</span> <span style="color:#008000; font-style:italic;"># =&gt; [&quot;@name&quot;]</span>
shabushabu.<span style="color:#9900CC;">origin</span> = <span style="color:#996600;">&quot;Japan&quot;</span>
shabushabu.<span style="color:#9900CC;">instance_variables</span> <span style="color:#008000; font-style:italic;"># =&gt; [&quot;@name&quot;, &quot;@origin&quot;]</span></pre></div></div>

<p>Another way of checking on the accessors is to check the methods defined on the object:</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;">shabushabu.<span style="color:#9900CC;">methods</span> <span style="color:#006600; font-weight:bold;">-</span> <span style="color:#CC00FF; font-weight:bold;">Object</span>.<span style="color:#9900CC;">new</span>.<span style="color:#9900CC;">methods</span>
<span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#006600; font-weight:bold;">&#91;</span><span style="color:#996600;">&quot;name&quot;</span>, <span style="color:#996600;">&quot;name=&quot;</span>, <span style="color:#996600;">&quot;origin&quot;</span>, <span style="color:#996600;">&quot;origin=&quot;</span>, <span style="color:#996600;">&quot;id=&quot;</span>, <span style="color:#996600;">&quot;query&quot;</span>, <span style="color:#996600;">&quot;query=&quot;</span><span style="color:#006600; font-weight:bold;">&#93;</span></pre></div></div>

<p>But anyway, this post isn&#8217;t about Ruby, it&#8217;s about Go and what we would like is to reflect on an object of &#8220;Dish&#8221; type and see its attributes. The good news is that the Go language ships with a <a title="Golang reflect package" href="http://golang.org/pkg/reflect/">package to do just that</a>. Here is the full implementation:</p>

<div class="wp_syntax"><div class="code"><pre class="c" style="font-family:monospace;">package main
&nbsp;
import<span style="color: #009900;">&#40;</span>
  <span style="color: #ff0000;">&quot;fmt&quot;</span>
  <span style="color: #ff0000;">&quot;reflect&quot;</span>
<span style="color: #009900;">&#41;</span>
&nbsp;
func main<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
  <span style="color: #666666; font-style: italic;">// iterate through the attributes of a Data Model instance</span>
  <span style="color: #b1b100;">for</span> name<span style="color: #339933;">,</span> mtype <span style="color: #339933;">:=</span> range attributes<span style="color: #009900;">&#40;</span><span style="color: #339933;">&amp;</span>Dish<span style="color: #009900;">&#123;</span><span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    fmt.<span style="color: #202020;">Printf</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;Name: %s, Type %s<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #339933;">,</span> name<span style="color: #339933;">,</span> mtype.<span style="color: #202020;">Name</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>
  <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// Data Model</span>
type Dish <span style="color: #993333;">struct</span> <span style="color: #009900;">&#123;</span>
  Id  <span style="color: #993333;">int</span>
  Name string
  Origin string
  Query func<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// Example of how to use Go's reflection</span>
<span style="color: #666666; font-style: italic;">// Print the attributes of a Data Model</span>
func attributes<span style="color: #009900;">&#40;</span>m interface<span style="color: #009900;">&#123;</span><span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#40;</span>map<span style="color: #009900;">&#91;</span>string<span style="color: #009900;">&#93;</span>reflect.<span style="color: #202020;">Type</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
  typ <span style="color: #339933;">:=</span> reflect.<span style="color: #202020;">TypeOf</span><span style="color: #009900;">&#40;</span>m<span style="color: #009900;">&#41;</span>
  <span style="color: #666666; font-style: italic;">// if a pointer to a struct is passed, get the type of the dereferenced object</span>
  <span style="color: #b1b100;">if</span> typ.<span style="color: #202020;">Kind</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">==</span> reflect.<span style="color: #202020;">Ptr</span><span style="color: #009900;">&#123;</span>
    typ <span style="color: #339933;">=</span> typ.<span style="color: #202020;">Elem</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
  <span style="color: #009900;">&#125;</span>
&nbsp;
  <span style="color: #666666; font-style: italic;">// create an attribute data structure as a map of types keyed by a string.</span>
  attrs <span style="color: #339933;">:=</span> make<span style="color: #009900;">&#40;</span>map<span style="color: #009900;">&#91;</span>string<span style="color: #009900;">&#93;</span>reflect.<span style="color: #202020;">Type</span><span style="color: #009900;">&#41;</span>
  <span style="color: #666666; font-style: italic;">// Only structs are supported so return an empty result if the passed object</span>
  <span style="color: #666666; font-style: italic;">// isn't a struct</span>
  <span style="color: #b1b100;">if</span> typ.<span style="color: #202020;">Kind</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">!=</span> reflect.<span style="color: #202020;">Struct</span> <span style="color: #009900;">&#123;</span>
    fmt.<span style="color: #202020;">Printf</span><span style="color: #009900;">&#40;</span><span style="color: #ff0000;">&quot;%v type can't have attributes inspected<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #339933;">,</span> typ.<span style="color: #202020;">Kind</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>
    <span style="color: #b1b100;">return</span> attrs
  <span style="color: #009900;">&#125;</span>
&nbsp;
  <span style="color: #666666; font-style: italic;">// loop through the struct's fields and set the map</span>
  <span style="color: #b1b100;">for</span> i <span style="color: #339933;">:=</span> <span style="color: #0000dd;">0</span><span style="color: #339933;">;</span> i <span style="color: #339933;">&lt;</span> typ.<span style="color: #202020;">NumField</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> i<span style="color: #339933;">++</span> <span style="color: #009900;">&#123;</span>
    p <span style="color: #339933;">:=</span> typ.<span style="color: #202020;">Field</span><span style="color: #009900;">&#40;</span>i<span style="color: #009900;">&#41;</span>
      <span style="color: #b1b100;">if</span> <span style="color: #339933;">!</span>p.<span style="color: #202020;">Anonymous</span> <span style="color: #009900;">&#123;</span>
        attrs<span style="color: #009900;">&#91;</span>p.<span style="color: #202020;">Name</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> p.<span style="color: #202020;">Type</span>
      <span style="color: #009900;">&#125;</span>
     <span style="color: #009900;">&#125;</span>
&nbsp;
  <span style="color: #b1b100;">return</span> attrs
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Unfortunately, my code highlighter doesn&#8217;t support the Go syntax, but GitHub does, so here is a <a title="Golang reflection" href="https://gist.github.com/1009629" target="_blank">pretty version</a>.</p>
<p>There are ways of running Go source code like Ruby or Python scripts but in this case, we&#8217;ll use the compiler &amp; linker provided with Go. I named my source file &#8220;example.go&#8221;, and here is how I compiled, linked and run it:</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;">$ 6g example.go <span style="color: #000000; font-weight: bold;">&amp;&amp;</span> 6l example.6 <span style="color: #000000; font-weight: bold;">&amp;&amp;</span> .<span style="color: #000000; font-weight: bold;">/</span><span style="color: #000000;">6</span>.out
Name: Origin, Type string
Name: Id, Type int
Name: Query, Type 
Name: Name, Type string</pre></div></div>

<p>As you can see each attribute is printed out with its name and type. The code might seem a bit odd if you never looked at Go before.<br />
Here is a quick rundown of the code:</p>
<p>In our main function, we create a new instance of type Dish on which we call attributes on. The call returns a map on which we iterate through and print the attribute name (key) and type (value).<br />
The attributes function is defined a bit below and and it takes any type of objects (empty interface) and returns a map, which is like a Hash or a Dictionary. The map has keys of String type and values of &#8220;Type&#8221; type. The &#8220;Type&#8221; type is defined in the reflect package. Inside the function, 23 then use the previously mentioned reflect package to check on the type and the name of each attribute and assign it to a map object. (note that I&#8217;m explicitly returning the map, but I could have done it in a more implicit way)</p>
<p>So there you go, that&#8217;s how you use reflection in Go. Pretty nifty and simple.</p>
<p>&nbsp;</p>
]]></content:encoded>
			<wfw:commentRss>http://merbist.com/2011/06/27/golang-reflection-exampl/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>MacRuby tips: browse for folder or file dialog</title>
		<link>http://merbist.com/2009/10/25/macruby-browse-for-folder-or-file-dialog/</link>
		<comments>http://merbist.com/2009/10/25/macruby-browse-for-folder-or-file-dialog/#comments</comments>
		<pubDate>Sun, 25 Oct 2009 23:52:14 +0000</pubDate>
		<dc:creator>Matt Aimonetti</dc:creator>
				<category><![CDATA[macruby]]></category>
		<category><![CDATA[Tutorial]]></category>
		<category><![CDATA[cocoa]]></category>
		<category><![CDATA[tip]]></category>

		<guid isPermaLink="false">http://merbist.com/?p=624</guid>
		<description><![CDATA[This is yet another pretty simple tip. Use case: let say you want your applications users to choose one or multiple files or folder on their file system. A good example would be that you want the user to choose a file to process or a folder where to save some data. In the example [...]]]></description>
			<content:encoded><![CDATA[<p>This is yet another pretty simple tip.<br />
Use case: let say you want your applications users to choose one or multiple files or folder on their file system. A good example would be that you want the user to choose a file to process or a folder where to save some data.</p>
<p><img class="aligncenter" title="MacRuby, file browser dialog" src="http://img.skitch.com/20091025-nc89xd2ywqutqqddnwm2met3x4.jpg" alt="" width="389" height="43" /></p>
<p>In the example above, I added a browse button and a text field.</p>
<p>I would like my users to click on the browse button, locate a folder and display it in the text field.</p>
<p>In your MacRuby controller, use a simple action method as well as an accessor to the text field:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
</pre></td><td class="code"><pre class="ruby" style="font-family:monospace;">attr_accessor <span style="color:#ff3333; font-weight:bold;">:destination_path</span>
&nbsp;
<span style="color:#9966CC; font-weight:bold;">def</span> browse<span style="color:#006600; font-weight:bold;">&#40;</span>sender<span style="color:#006600; font-weight:bold;">&#41;</span>
<span style="color:#9966CC; font-weight:bold;">end</span></pre></td></tr></table></div>

<p>Now, in Interface builder bind the destination_path outlet to the text field you want to use to display the path and bind the button to the browse action.</p>
<p>Let&#8217;s go back to our action method and let&#8217;s create a dialog panel, set some options and handle the user selection:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
</pre></td><td class="code"><pre class="ruby" style="font-family:monospace;"><span style="color:#9966CC; font-weight:bold;">def</span> browse<span style="color:#006600; font-weight:bold;">&#40;</span>sender<span style="color:#006600; font-weight:bold;">&#41;</span>
  <span style="color:#008000; font-style:italic;"># Create the File Open Dialog class.</span>
  dialog = NSOpenPanel.<span style="color:#9900CC;">openPanel</span>
  <span style="color:#008000; font-style:italic;"># Disable the selection of files in the dialog.</span>
  dialog.<span style="color:#9900CC;">canChooseFiles</span> = <span style="color:#0000FF; font-weight:bold;">false</span>
  <span style="color:#008000; font-style:italic;"># Enable the selection of directories in the dialog.</span>
  dialog.<span style="color:#9900CC;">canChooseDirectories</span> = <span style="color:#0000FF; font-weight:bold;">true</span>
  <span style="color:#008000; font-style:italic;"># Disable the selection of multiple items in the dialog.</span>
  dialog.<span style="color:#9900CC;">allowsMultipleSelection</span> = <span style="color:#0000FF; font-weight:bold;">false</span>
&nbsp;
  <span style="color:#008000; font-style:italic;"># Display the dialog and process the selected folder</span>
  <span style="color:#9966CC; font-weight:bold;">if</span> dialog.<span style="color:#9900CC;">runModalForDirectory</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#0000FF; font-weight:bold;">nil</span>, file:<span style="color:#0000FF; font-weight:bold;">nil</span><span style="color:#006600; font-weight:bold;">&#41;</span> == NSOKButton
  <span style="color:#008000; font-style:italic;"># if we had a allowed for the selection of multiple items</span>
  <span style="color:#008000; font-style:italic;"># we would have want to loop through the selection</span>
    destination_path.<span style="color:#9900CC;">stringValue</span> = dialog.<span style="color:#9900CC;">filenames</span>.<span style="color:#9900CC;">first</span>
  <span style="color:#9966CC; font-weight:bold;">end</span>
<span style="color:#9966CC; font-weight:bold;">end</span></pre></td></tr></table></div>

<p>That&#8217;s it, your user can now browse for a folder and the selection will be displayed in the text field. Look at the <a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/ApplicationKit/Classes/NSOpenPanel_Class/Reference/Reference.html" target="_blank">NSOpenPanel documentation</a> for more details on the Cocoa API.</p>
]]></content:encoded>
			<wfw:commentRss>http://merbist.com/2009/10/25/macruby-browse-for-folder-or-file-dialog/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>MacRuby tips: capturing keyboard events</title>
		<link>http://merbist.com/2009/10/09/macruby-tips-capturing-keyboard-events/</link>
		<comments>http://merbist.com/2009/10/09/macruby-tips-capturing-keyboard-events/#comments</comments>
		<pubDate>Sat, 10 Oct 2009 03:24:04 +0000</pubDate>
		<dc:creator>Matt Aimonetti</dc:creator>
				<category><![CDATA[macruby]]></category>
		<category><![CDATA[Tutorial]]></category>

		<guid isPermaLink="false">http://merbist.com/?p=602</guid>
		<description><![CDATA[If you are writing any type of games you might want your users to interact with your application using their keyboards. This is actually not that hard. The approach is simple and fast forward if you are used to Cocoa. Everything starts in Interface Builder, add a custom view instance to your window. Now switch [...]]]></description>
			<content:encoded><![CDATA[<p>If you are writing any type of games you might want your users to interact with your application using their keyboards.</p>
<p>This is actually not that hard. The approach is simple and fast forward if you are used to Cocoa.</p>
<p>Everything starts in Interface Builder, add a custom view instance to your window.</p>
<p><img class="aligncenter" src="http://img.skitch.com/20091010-8tf834wf9se6y81h2jf7a7e5he.jpg" alt="" width="270" height="554" /></p>
<p>Now switch to your project and a new file with a class called KeyboardControlView and make in inherit from NSView. We are creating a subview of NSView so we will be able to make our top view &#8220;layer&#8221; use this subclass.</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;"><span style="color:#9966CC; font-weight:bold;">class</span> KeyboardControlView <span style="color:#006600; font-weight:bold;">&amp;</span>lt; NSView
  attr_accessor <span style="color:#ff3333; font-weight:bold;">:game_controller</span>
&nbsp;
  <span style="color:#9966CC; font-weight:bold;">def</span> acceptsFirstResponder
    <span style="color:#0000FF; font-weight:bold;">true</span>
  <span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
<span style="color:#9966CC; font-weight:bold;">end</span></pre></div></div>

<p>As you can see in the example above, I added an attribute accessor. attr_accessor class method creates getters and setters. It&#8217;s basically the same as writing:</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;"> <span style="color:#9966CC; font-weight:bold;">def</span> game_controller=<span style="color:#006600; font-weight:bold;">&#40;</span>value<span style="color:#006600; font-weight:bold;">&#41;</span>
  <span style="color:#0066ff; font-weight:bold;">@game_controller</span> = value
<span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
<span style="color:#9966CC; font-weight:bold;">def</span> game_controller
  <span style="color:#0066ff; font-weight:bold;">@game_controller</span>
<span style="color:#9966CC; font-weight:bold;">end</span></pre></div></div>

<p>MacRuby is keeping an eye on these accessors and let bind outlets to them.<br />
But let&#8217;s not get ahead of ourselves, we&#8217;ll keep that for another time.</p>
<p>Let&#8217;s go back to our newly created class. Notice, we also added a method called `<br />
<a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/ApplicationKit/Classes/NSResponder_Class/Reference/Reference.html#//apple_ref/occ/instm/NSResponder/acceptsFirstResponder" target="_blank">acceptsFirstResponder</a>` and returns true. <a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/ApplicationKit/Classes/NSResponder_Class/Reference/Reference.html#//apple_ref/occ/instm/NSResponder/acceptsFirstResponder" target="_blank">acceptsFirstResponder</a> returns false by default.<br />
But in this case we want it to return true so our new class instance can be first in the responder chain.</p>
<p>Now that our class is ready, let&#8217;s go back to Interface Builder, select our new custom view and click on the inspector button.</p>
<p><img class="aligncenter" title="IB" src="http://img.skitch.com/20091010-1trkxhw2r2paaik3ipa4gtytgg.jpg" alt="" width="228" height="184" /><br />
Click on the (i) icon and in the Class field choose our new KeyboardControlView.<br />
Yep, our new class just shows up by magic, it&#8217;s also called the lrz effect, just don&#8217;t ask <img src='http://merbist.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /><br />
So now when our application starts, a new instance of our NSView class is created and Cocoa will call different methods based on events triggered.</p>
<p>The two methods we are interested in reimplementing are keyDown and keyUp. They get called when a key gets pressed or released.</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;"><span style="color:#9966CC; font-weight:bold;">def</span> keyDown<span style="color:#006600; font-weight:bold;">&#40;</span>event<span style="color:#006600; font-weight:bold;">&#41;</span>
  characters = event.<span style="color:#9900CC;">characters</span>
  <span style="color:#9966CC; font-weight:bold;">if</span> characters.<span style="color:#9900CC;">length</span> == <span style="color:#006666;">1</span> <span style="color:#006600; font-weight:bold;">&amp;</span>amp;<span style="color:#006600; font-weight:bold;">&amp;</span>amp; !event.<span style="color:#9900CC;">isARepeat</span>
    character = characters.<span style="color:#9900CC;">characterAtIndex</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#006666;">0</span><span style="color:#006600; font-weight:bold;">&#41;</span>
    <span style="color:#9966CC; font-weight:bold;">if</span> character == NSLeftArrowFunctionKey
      <span style="color:#CC0066; font-weight:bold;">puts</span> <span style="color:#996600;">&quot;LEFT pressed&quot;</span>
    <span style="color:#9966CC; font-weight:bold;">elsif</span> character == NSRightArrowFunctionKey
      <span style="color:#CC0066; font-weight:bold;">puts</span> <span style="color:#996600;">&quot;RIGHT pressed&quot;</span>
    <span style="color:#9966CC; font-weight:bold;">elsif</span> character == NSUpArrowFunctionKey
      <span style="color:#CC0066; font-weight:bold;">puts</span> <span style="color:#996600;">&quot;UP pressed&quot;</span>
    <span style="color:#9966CC; font-weight:bold;">elsif</span> character == NSDownArrowFunctionKey
      <span style="color:#CC0066; font-weight:bold;">puts</span> <span style="color:#996600;">&quot;DOWN pressed&quot;</span>
    <span style="color:#9966CC; font-weight:bold;">end</span>
  <span style="color:#9966CC; font-weight:bold;">end</span>
 <span style="color:#9966CC; font-weight:bold;">super</span>
<span style="color:#9966CC; font-weight:bold;">end</span></pre></div></div>

<p>I don&#8217;t think the code above needs much explanation. The only things that you might not understand are &#8216;event.isARepeat&#8217;. This method returns true if the user left his/her finger on the key. The other thing is the use of the &#8216;super&#8217; call at the end of the method. Basically, we reopened a method that was already defined and we don&#8217;t want to just overwrite it, we just want to inject out code within the existing method, so once we are done handling the event, we just pass it back to original method.</p>
<p>Final result:</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;"><span style="color:#9966CC; font-weight:bold;">class</span> KeyboardControlView <span style="color:#006600; font-weight:bold;">&amp;</span>lt; NSView
  attr_accessor <span style="color:#ff3333; font-weight:bold;">:game_controller</span>
&nbsp;
  <span style="color:#9966CC; font-weight:bold;">def</span> acceptsFirstResponder
    <span style="color:#0000FF; font-weight:bold;">true</span>
  <span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
  <span style="color:#9966CC; font-weight:bold;">def</span> keyDown<span style="color:#006600; font-weight:bold;">&#40;</span>event<span style="color:#006600; font-weight:bold;">&#41;</span>
    characters = event.<span style="color:#9900CC;">characters</span>
    <span style="color:#9966CC; font-weight:bold;">if</span> characters.<span style="color:#9900CC;">length</span> == <span style="color:#006666;">1</span> <span style="color:#006600; font-weight:bold;">&amp;</span>amp;<span style="color:#006600; font-weight:bold;">&amp;</span>amp; !event.<span style="color:#9900CC;">isARepeat</span>
      character = characters.<span style="color:#9900CC;">characterAtIndex</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#006666;">0</span><span style="color:#006600; font-weight:bold;">&#41;</span>
      <span style="color:#9966CC; font-weight:bold;">if</span> character == NSLeftArrowFunctionKey
        <span style="color:#CC0066; font-weight:bold;">puts</span> <span style="color:#996600;">&quot;LEFT pressed&quot;</span>
      <span style="color:#9966CC; font-weight:bold;">elsif</span> character == NSRightArrowFunctionKey
        <span style="color:#CC0066; font-weight:bold;">puts</span> <span style="color:#996600;">&quot;RIGHT pressed&quot;</span>
      <span style="color:#9966CC; font-weight:bold;">elsif</span> character == NSUpArrowFunctionKey
        <span style="color:#CC0066; font-weight:bold;">puts</span> <span style="color:#996600;">&quot;UP pressed&quot;</span>
      <span style="color:#9966CC; font-weight:bold;">elsif</span> character == NSDownArrowFunctionKey
  	<span style="color:#CC0066; font-weight:bold;">puts</span> <span style="color:#996600;">&quot;DOWN pressed&quot;</span>
      <span style="color:#9966CC; font-weight:bold;">end</span>
    <span style="color:#9966CC; font-weight:bold;">end</span>
    <span style="color:#9966CC; font-weight:bold;">super</span>
  <span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
  <span style="color:#008000; font-style:italic;"># Deals with keyboard keys being released</span>
  <span style="color:#9966CC; font-weight:bold;">def</span> keyUp<span style="color:#006600; font-weight:bold;">&#40;</span>event<span style="color:#006600; font-weight:bold;">&#41;</span>
    characters = event.<span style="color:#9900CC;">characters</span>
    <span style="color:#9966CC; font-weight:bold;">if</span> characters.<span style="color:#9900CC;">length</span> == <span style="color:#006666;">1</span>
      character = characters.<span style="color:#9900CC;">characterAtIndex</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#006666;">0</span><span style="color:#006600; font-weight:bold;">&#41;</span>
      <span style="color:#9966CC; font-weight:bold;">if</span> character == NSLeftArrowFunctionKey
       <span style="color:#CC0066; font-weight:bold;">puts</span> <span style="color:#996600;">&quot;LEFT released&quot;</span>
      <span style="color:#9966CC; font-weight:bold;">elsif</span> character == NSRightArrowFunctionKey
        <span style="color:#CC0066; font-weight:bold;">puts</span> <span style="color:#996600;">&quot;RIGHT released&quot;</span>
      <span style="color:#9966CC; font-weight:bold;">elsif</span> character == NSUpArrowFunctionKey
       <span style="color:#CC0066; font-weight:bold;">puts</span> <span style="color:#996600;">&quot;UP released&quot;</span>
      <span style="color:#9966CC; font-weight:bold;">elsif</span> character == NSDownArrowFunctionKey
        <span style="color:#CC0066; font-weight:bold;">puts</span> <span style="color:#996600;">&quot;DOWN released&quot;</span>
      <span style="color:#9966CC; font-weight:bold;">end</span>
    <span style="color:#9966CC; font-weight:bold;">end</span>
    <span style="color:#9966CC; font-weight:bold;">super</span>
  <span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
<span style="color:#9966CC; font-weight:bold;">end</span></pre></div></div>

<p>Now it&#8217;s up to you to handle the other keystrokes and do whatever you want. That&#8217;s it for this tip, I hope it helps.</p>
]]></content:encoded>
			<wfw:commentRss>http://merbist.com/2009/10/09/macruby-tips-capturing-keyboard-events/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Ruby, Rack and CouchDB = lots of awesomeness</title>
		<link>http://merbist.com/2009/07/27/ruby-rack-and-couchdb-lots-of-awesomeness/</link>
		<comments>http://merbist.com/2009/07/27/ruby-rack-and-couchdb-lots-of-awesomeness/#comments</comments>
		<pubDate>Mon, 27 Jul 2009 21:49:20 +0000</pubDate>
		<dc:creator>Matt Aimonetti</dc:creator>
				<category><![CDATA[merb]]></category>
		<category><![CDATA[Misc]]></category>
		<category><![CDATA[rails]]></category>
		<category><![CDATA[ruby]]></category>
		<category><![CDATA[Tutorial]]></category>
		<category><![CDATA[couchdb]]></category>
		<category><![CDATA[logging]]></category>
		<category><![CDATA[rack]]></category>
		<category><![CDATA[rails3]]></category>
		<category><![CDATA[railssummit]]></category>

		<guid isPermaLink="false">http://merbist.com/?p=536</guid>
		<description><![CDATA[Over the weekend, I spent some time working on a Ruby + Rack +CouchDB project. Three technologies that I know quite well but that I never put to work together at the same time, at least not directly.  Let&#8217;s call this Part I. Before we get started, let me introduce each component: Ruby : if [...]]]></description>
			<content:encoded><![CDATA[<p>Over the weekend, I spent some time working on a Ruby + Rack +CouchDB project. Three technologies that I know quite well but that I never put to work together at the same time, at least not directly.  Let&#8217;s call this Part I.</p>
<p>Before we get started, let me introduce each component:</p>
<ul>
<li><a id="aptureLink_uhrplaQzyi" href="http://en.wikipedia.org/wiki/Ruby%20%28programming%20language%29">Ruby</a> : if you are reading this blog, you more than likely know at least a little bit about, what I consider, one of the most enjoyable programming language out there. It&#8217;s also a very flexible language that lets us do some interesting things. I could have chosen Python to do the same project but that&#8217;s a whole different topic. For this project we will do something Ruby excels at: reopening existing classes and injecting more code.</li>
<li><a id="aptureLink_2DDeKXxZsP" href="http://rack.rubyforge.org/">Rack</a>: a webserver interface written in Ruby and inspired by <a id="aptureLink_Jchqx9HIiw" href="http://www.wsgi.org/wsgi/">Python&#8217;s WSGI</a>. Basically, it&#8217;s a defined API to interact between webservers and web frameworks. <span style="color: #000000;">It&#8217;s used by most common Ruby web frameworks, from Sinatra to Rails</span> (btw, Rails3 is going to be even more Rack-focused than it already is). So, very simply put, the webserver receives a request, passes it to Rack, that converts it, passes it to your web framework and the web framework sends a response in the expected format (more on Rack later).</li>
<li><a id="aptureLink_LN4oL6D0oH" href="http://couchdb.apache.org/">CouchDB</a>: Apache&#8217;s document-oriented database. RESTful API, schema-less, written in Erlang with built-in support for map/reduce. For this project, I&#8217;m using <a id="aptureLink_tlTW2NkUta" href="http://github.com/mattetti/couchrest">CouchRest</a>, a Ruby wrapper for Couch.</li>
</ul>
<h2>Goal: Log Couch requests and analyze data</h2>
<p>Let&#8217;s say we have a Rails, Sinatra or Merb application and we are using CouchRest (maybe we are using CouchRest and ActiveRecord, but let&#8217;s ignore that for now).</p>
<p>Everything works fine but we would like to profile our app a little and maybe optimize the DB usage. The default framework loggers don&#8217;t support Couch. The easy way would be to tail the Couch logs or look at the logs in <a id="aptureLink_W2ygfTNmX0" href="http://janl.github.com/couchdbx/">CouchDBX</a>. Now, while that works, we can&#8217;t really see what DB calls are made per action, so it makes any optimization work a bit tedious. (Note that Rails3 will have some better conventions for logging, making things even easier)</p>
<p>So, let&#8217;s see how to fix that. Let&#8217;s start by looking at Rack.</p>
<h2>Rack Middleware</h2>
<p>Instead of hacking a web framework specific solution, let&#8217;s use Rack. Rack is dead simple, you just need to write a class that has a <em>call</em> method.<br />
<script src="http://gist.github.com/155420.js"></script> In our case, we don&#8217;t care about modifying the response, we just want to instrument our app. We just want our middleware to be transparent and let our webserver deal with it normally.    <script src="http://gist.github.com/155425.js"></script></p>
<p>Here we go &#8230; that wasn&#8217;t hard, was it? We keep the application reference in the @app variable when a new instance of the middleware is created. Then when the middleware is called, we just call the rest of the chain and pretend nothing happened.</p>
<p><script src="http://gist.github.com/155432.js"></script> As you can see, we just added some logging info around the request. Let&#8217;s do one better and save the logs in CouchDB:  <script src="http://gist.github.com/155437.js"></script></p>
<p>Again, nothing complicated. In our rackup file we defined which Couch database to use and we passed it to our middleware (we change our initialize method signature to take the DB).<br />
Finally, instead of printing out the logs, we are saving them to the database.</p>
<p>W00t! At this point all our requests have been saved in the DB with all the data there, ready to be manipulated by some map/reduce views we will write. For the record, you might want to use the bulk_save approach in CouchDB which will wait for X amount of records to save them in the DB all at once. Couch also let&#8217;s you send new documents, but only save it to the DB every X documents or X seconds.</p>
<p><img class="alignnone" title="log document" src="http://img.skitch.com/20090726-ebmpgjtrc6x8239ia69kmri1rt.jpg" alt="" width="715" height="505" /></p>
<p>As you can see, our document contains the timestamps and the full environment as a hash.</p>
<p>All of that is nice, but even though we get a lot of information, we could not actually see any of the DB calls made in each request. Let&#8217;s fix that and inject our logger in CouchRest (you could apply the same approach to any adapter).</p>
<p>Let&#8217;s reopen the HTTP Abstraction layer class used by CouchRest and inject some instrumentation:</p>
<p><script src="http://gist.github.com/155442.js"></script></p>
<p>Again, nothing fancy, we are just opening the module, reopening the methods and wrapping our code around the <em>super</em> call (for those who don&#8217;t know, <em>super</em> calls the original method).</p>
<p>This is all for Part I. In Part II, we&#8217;ll see how to process the logs and make all that data useful.</p>
<p>By the way, if you make it to <a id="aptureLink_aF4OSFnjjA" href="http://www.railssummit.com.br/">RailsSummit</a>, I will be giving a talk on Rails3 and the new exciting stuff you will be able to do including Rack based stuff, CouchDB, MongoDB, new DataMapper etc..</p>
<p><a href="http://railssummit.com.br/"><img class="aligncenter" title="RailsSummit 2009" src="http://railssummit.com.br/images/banners/en_souPalestrante_210x60.jpg" alt="" width="210" height="60" /></a></p>
]]></content:encoded>
			<wfw:commentRss>http://merbist.com/2009/07/27/ruby-rack-and-couchdb-lots-of-awesomeness/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Get on Merb Edge pre 1.0</title>
		<link>http://merbist.com/2008/10/04/get-on-merb-edge-pre-10/</link>
		<comments>http://merbist.com/2008/10/04/get-on-merb-edge-pre-10/#comments</comments>
		<pubDate>Sat, 04 Oct 2008 21:00:01 +0000</pubDate>
		<dc:creator>Matt Aimonetti</dc:creator>
				<category><![CDATA[Tutorial]]></category>
		<category><![CDATA[datamapper]]></category>
		<category><![CDATA[edge]]></category>
		<category><![CDATA[merb]]></category>
		<category><![CDATA[thor]]></category>

		<guid isPermaLink="false">http://merbist.com/?p=114</guid>
		<description><![CDATA[Merb 1.0 is almost ready to be pushed out and you might be impatient to start playing with some of the goodies not yet available in the latest stable release. Before getting started, you should know that not everything has been ironed out yet so don&#8217;t expect to have a fully stable Edge. The easiest [...]]]></description>
			<content:encoded><![CDATA[<p>Merb 1.0 is almost ready to be pushed out and you might be impatient to start playing with some of the goodies not yet available in the latest stable release. Before getting started, you should know that not everything has been ironed out yet so don&#8217;t expect to have a fully stable Edge.</p>
<p>The easiest way to get started requires that you have <a title="Git" href="http://git.or.cz/" target="_blank">git</a> installed as well as a gem called <a title="thor" href="http://github.com/wycats/thor/tree/master" target="_blank">thor</a>.</p>
<p>I let you take care of installing git on your machine, Ruby dev without git became quite challenging since <a title="GitHub" href="http://github.com" target="_blank">GitHub</a> started ruling the Ruby OSS world.</p>
<pre><code class="shell">sudo gem install wycats-thor -s http://gems.github.com</code></pre>
<div class="wp-caption alignright" style="width: 250px"><a href="http://flickr.com/photos/fturmog/1438235253/"><img title="Hops" src="http://farm2.static.flickr.com/1418/1438235253_5b10c24732_m.jpg" alt="Hops, used primarily as a flavoring and stability agent in beer, and also in other beverages and in herbal medicine." width="240" height="180" /></a><p class="wp-caption-text">Hops, used primarily as a flavoring and stability agent in beer, and also in other beverages and in herbal medicine.</p></div>
<p><a title="thor" href="http://yehudakatz.com/2008/05/12/by-thors-hammer/" target="_blank">Thor</a> is a sort if mix between rake, <a title="sake" href="http://errtheblog.com/posts/60-sake-bomb" target="_blank">sake</a> with a better argument parser and based on Ruby classes.</p>
<p>Thor on its own won&#8217;t be very helpful, we need some thor tasks.</p>
<p>Create a folder where you want to store Merb&#8217;s source code and cd in it.</p>
<p>Once there download the latest merb thor tasks:</p>
<pre><code class="shell">curl -L http://merbivore.com/merb.thor &gt; merb.thor
</code></pre>
<p>You can now look at the available task by doing</p>
<pre><code class="shell">thor -T</code></pre>
<p><span id="more-114"></span><br />
At this point you be overwhelmed by the multitude of options, we are working on making things a be nicer for 1.0. But anyways, let&#8217;s get started:</p>
<pre><code class="shell">sudo thor merb:edge --install</code></pre>
<p>The command above will install extlib, merb-core and merb-more from git HEAD. You now have the latest version of Merb&#8217;s libs installed locally as gems.</p>
<p>You might also want to install Merb extra plugins, if that&#8217;s the case do:</p>
<pre><code class="shell"> sudo thor merb:edge:plugins --install</code></pre>
<p>If you decided to use DataMapper instead of ActiveRecord or Sequel, you will also need to install the gems you might need:</p>
<p>Install data_objects and an adapter: (replace mysql by the adapter you want to install)</p>
<pre><code class="shell"> sudo thor merb:edge:do mysql --install</code></pre>
<p>Install DataMapper core from Git HEAD</p>
<pre><code class="shell"> sudo thor merb:edge:dm_core --install</code></pre>
<p>Install DataMapper more from Git HEAD</p>
<pre><code class="shell"> sudo thor merb:edge:dm_more --install</code></pre>
<p>You should be all setup by now.</p>
<p><strong><br />
Next time you want to update, just come back to the same folder and do the same thing. Hopefully by then we will have a 1 task solution and will offer a merb-stack version of our gems to let you install everything at once with all setup done.</strong></p>
<p>p.s: this post is dedicated <a title="Derek Neighbors" href="http://derekneighbors.com/" target="_blank">Derek Neighbors</a> <img src='http://merbist.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://merbist.com/2008/10/04/get-on-merb-edge-pre-10/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>problems with urls in Merb HEAD?</title>
		<link>http://merbist.com/2008/09/30/problems-with-urls-in-merb-head/</link>
		<comments>http://merbist.com/2008/09/30/problems-with-urls-in-merb-head/#comments</comments>
		<pubDate>Wed, 01 Oct 2008 06:24:29 +0000</pubDate>
		<dc:creator>Matt Aimonetti</dc:creator>
				<category><![CDATA[Misc]]></category>
		<category><![CDATA[Tutorial]]></category>
		<category><![CDATA[merb]]></category>
		<category><![CDATA[merb-assets]]></category>
		<category><![CDATA[router]]></category>

		<guid isPermaLink="false">http://merbist.com/?p=101</guid>
		<description><![CDATA[I actually run into a small problem when updated an older Merb app. Here was how my router looked like: Merb::Router.prepare do &#124;r&#124; r.resources :channels do &#124;channels&#124; channels.resources :shows do &#124;shows&#124; shows.resources :episodes end end end But after updating to the latest version of Merb, I got links looking like: http://localhost:4000/channels/#&#60;Channel:0x27b7300&#62;/shows The first thing to [...]]]></description>
			<content:encoded><![CDATA[<p>I actually run into a small problem when updated an older Merb app. Here was how my router looked like:</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;"><span style="color:#6666ff; font-weight:bold;">Merb::Router</span>.<span style="color:#9900CC;">prepare</span> <span style="color:#9966CC; font-weight:bold;">do</span> <span style="color:#006600; font-weight:bold;">|</span>r<span style="color:#006600; font-weight:bold;">|</span>
  r.<span style="color:#9900CC;">resources</span> <span style="color:#ff3333; font-weight:bold;">:channels</span> <span style="color:#9966CC; font-weight:bold;">do</span> <span style="color:#006600; font-weight:bold;">|</span>channels<span style="color:#006600; font-weight:bold;">|</span>
    channels.<span style="color:#9900CC;">resources</span> <span style="color:#ff3333; font-weight:bold;">:shows</span> <span style="color:#9966CC; font-weight:bold;">do</span> <span style="color:#006600; font-weight:bold;">|</span>shows<span style="color:#006600; font-weight:bold;">|</span>
      shows.<span style="color:#9900CC;">resources</span> <span style="color:#ff3333; font-weight:bold;">:episodes</span>
    <span style="color:#9966CC; font-weight:bold;">end</span>
  <span style="color:#9966CC; font-weight:bold;">end</span>
<span style="color:#9966CC; font-weight:bold;">end</span></pre></div></div>

<p>But after updating to the latest version of Merb, I got links looking like:</p>
<pre>http://localhost:4000/channels/#&lt;Channel:0x27b7300&gt;/shows</pre>
<p>The first thing to do is to read <a title="new router" href="http://github.com/carllerche/merb-core-enterprise-edition/wikis/whats-new-with-the-router" target="_blank">Carl&#8217;s wiki about the latest Router changes</a>.</p>
<p>Carl explains that things got cleaned up in the router code and my routes should now look like:</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;"><span style="color:#6666ff; font-weight:bold;">Merb::Router</span>.<span style="color:#9900CC;">prepare</span> <span style="color:#9966CC; font-weight:bold;">do</span> <span style="color:#006600; font-weight:bold;">|</span>r<span style="color:#006600; font-weight:bold;">|</span>
  r.<span style="color:#9900CC;">resources</span> <span style="color:#ff3333; font-weight:bold;">:channels</span> <span style="color:#9966CC; font-weight:bold;">do</span>
    resources <span style="color:#ff3333; font-weight:bold;">:shows</span> <span style="color:#9966CC; font-weight:bold;">do</span> <span style="color:#006600; font-weight:bold;">|</span>shows<span style="color:#006600; font-weight:bold;">|</span>
      resources <span style="color:#ff3333; font-weight:bold;">:episodes</span>
    <span style="color:#9966CC; font-weight:bold;">end</span>
  <span style="color:#9966CC; font-weight:bold;">end</span>
<span style="color:#9966CC; font-weight:bold;">end</span></pre></div></div>

<p>However that won&#8217;t be enough..  You see my url used to look like that:</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;">url<span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#ff3333; font-weight:bold;">:channel_shows</span>, <span style="color:#ff3333; font-weight:bold;">:channel_id</span> =<span style="color:#006600; font-weight:bold;">&amp;</span>gt; channel<span style="color:#006600; font-weight:bold;">&#41;</span></pre></div></div>

<p>Now I can simplify it to:</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;">url<span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#ff3333; font-weight:bold;">:channel_shows</span>, channel<span style="color:#006600; font-weight:bold;">&#41;</span></pre></div></div>

<p>That still won&#8217;t fix the problem, since the real problem comes from the fact that I was on Merb HEAD but not DataMapper HEAD. Updating DM clears things up. That&#8217;s the price to pay to be on HEAD <img src='http://merbist.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
<p>FYI the problem comes from the fact that DM doesn&#8217;t add a to_params method to its objects. Rails users might recognize that method used to convert an object into a string to create a route, something not really ORM agnostic and frowned upon by the DM/Merb teams.</p>
<p>Merb lets you specify the param to use for your routes using the identify method. Read <a title="new router" href="http://github.com/carllerche/merb-core-enterprise-edition/wikis/whats-new-with-the-router" target="_blank">Carl&#8217;s wiki page </a>for more cool stuff and see how to create some cool stuff like url slugs etc..</p>
<p>Note that even if you are using ActiveRecord, you&#8217;ll need to update merb_activerecord as the new identify rules were updated in the ORM plugins.</p>
]]></content:encoded>
			<wfw:commentRss>http://merbist.com/2008/09/30/problems-with-urls-in-merb-head/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Write your own custom DataMapper adapter</title>
		<link>http://merbist.com/2008/09/29/write-your-own-custom-datamapper-adapter/</link>
		<comments>http://merbist.com/2008/09/29/write-your-own-custom-datamapper-adapter/#comments</comments>
		<pubDate>Mon, 29 Sep 2008 08:38:46 +0000</pubDate>
		<dc:creator>Matt Aimonetti</dc:creator>
				<category><![CDATA[News]]></category>
		<category><![CDATA[Tutorial]]></category>
		<category><![CDATA[adapter]]></category>
		<category><![CDATA[datamapper]]></category>
		<category><![CDATA[google video]]></category>

		<guid isPermaLink="false">http://merbist.com/?p=91</guid>
		<description><![CDATA[If you read this blog, you probably know that Merb&#8216;s best ORM friend is DataMapper. Merb works very well with ActiveRecord and Sequel but most of the Merbivores get excited about DataMapper. DataMapper has a lot of cool stuff going for it. I&#8217;m planning on writingi few articles about what I particularily like with DM [...]]]></description>
			<content:encoded><![CDATA[<p>If you read this blog, you probably know that <a title="merb" href="http://merbivore.com" target="_blank">Merb</a>&#8216;s best <a title="ORM" href="http://en.wikipedia.org/wiki/Object-relational_mapping" target="_blank">ORM</a> friend is <a title="datamapper" href="http://datamapper.org/" target="_blank">DataMapper</a>.</p>
<div class="wp-caption alignleft" style="width: 250px"><a href="http://flickr.com/photos/darn/190457943/"><img title="Basil" src="http://farm1.static.flickr.com/55/190457943_8b93fda9e6_m.jpg" alt="compounds in basil oil have potent antioxidant and is used for supplementary treatment of stress" width="240" height="180" /></a><p class="wp-caption-text">compounds in basil oil have potent antioxidant and is used for supplementary treatment of stress</p></div>
<p>Merb works very well with ActiveRecord and Sequel but most of the Merbivores get excited about <a title="datamapper" href="http://datamapper.org/" target="_blank">DataMapper</a>.</p>
<p>DataMapper has a lot of cool stuff going for it. I&#8217;m planning on writingi few articles about what I particularily like with DM and some of the misconceptions.</p>
<p>I&#8217;m going to give a talk about DataMapper during <a title="MerbCamp" href="http://merbcamp.com" target="_blank">MerbCamp</a> and something I want to cover is the fact that you can write DM adapters for virtually anything. From an adapter for couchdb (available in dm-more) to an <a title="salesforce adapter" href="http://github.com/wycats/dm-adapters/tree/master/salesforce" target="_blank">adapter for SalesForce API</a>. That&#8217;s the kind of stuff that gets me excited, a bit like what <a title="Ambition" href="http://ambition.rubyforge.org/" target="_blank">Ambition</a> does but built-in in DM.</p>
<p>So, I decided to take some advise from <a title="Yehuda Katz" href="http://yehudakatz.com/" target="_blank">Yehuda</a> and dkubb and wrote my own adapter for <a title="Google Video" href="http://video.google.com" target="_blank">Google Video</a>. I had just finished a <a title="Gvideo" href="http://github.com/mattetti/gvideo" target="_blank">gem to retrieve google videos</a> for a given google user and thought it would be a perfect exercise to mix a <a title="scraper" href="http://en.wikipedia.org/wiki/Screen_scraping" target="_blank">http-scraper</a> with a DM adapter.</p>
<p><span id="more-91"></span></p>
<p>Based on the advise I received, I started by defining the API I want to use:</p>
<div class="code"><script src="http://gist.github.com/13571.js"></script></div>
<p>I matched the API calls to the underlying methods I would need to make. I then modified my original gem to support conditional calls.</p>
<p>Once that was done I implemented the required methods for my models to support the Model.first and Model.all calls with conditions.</p>
<p>A custom adapter inherits from<span class="no"> <a title="AbstractAdapter" href="http://github.com/sam/dm-core/tree/master/lib/dm-core/adapters/abstract_adapter.rb" target="_blank">AbstractAdapter</a></span> and can define the default adapter methods:</p>
<pre>
<div id="LC9" class="line">Â Â Â Â Â Â <span class="k">def</span> <span class="nf">create</span><span class="p">(</span><span class="n">resources</span><span class="p">)</span></div>
<div id="LC10" class="line">Â Â Â Â Â Â Â Â <span class="k">raise</span> <span class="no">NotImplementedError</span></div>
<div id="LC11" class="line">Â Â Â Â Â Â <span class="k">end</span></div>
<div id="LC13" class="line">Â Â Â Â Â Â <span class="k">def</span> <span class="nf">read_many</span><span class="p">(</span><span class="n">query</span><span class="p">)</span></div>
<div id="LC14" class="line">Â Â Â Â Â Â Â Â <span class="k">raise</span> <span class="no">NotImplementedError</span></div>
<div id="LC15" class="line">Â Â Â Â Â Â <span class="k">end</span></div>
<div id="LC17" class="line">Â Â Â Â Â Â <span class="k">def</span> <span class="nf">read_one</span><span class="p">(</span><span class="n">query</span><span class="p">)</span></div>
<div id="LC18" class="line">Â Â Â Â Â Â Â Â <span class="k">raise</span> <span class="no">NotImplementedError</span></div>
<div id="LC19" class="line">Â Â Â Â Â Â <span class="k">end</span></div>
<div id="LC21" class="line">Â Â Â Â Â Â <span class="k">def</span> <span class="nf">update</span><span class="p">(</span><span class="n">attributes</span><span class="p">,</span> <span class="n">query</span><span class="p">)</span></div>
<div id="LC22" class="line">Â Â Â Â Â Â Â Â <span class="k">raise</span> <span class="no">NotImplementedError</span></div>
<div id="LC23" class="line">Â Â Â Â Â Â <span class="k">end</span></div>
<div id="LC25" class="line">Â Â Â Â Â Â <span class="k">def</span> <span class="nf">delete</span><span class="p">(</span><span class="n">query</span><span class="p">)</span></div>
<div id="LC26" class="line">Â Â Â Â Â Â Â Â <span class="k">raise</span> <span class="no">NotImplementedError</span></div>
<div id="LC27" class="line">Â Â Â Â Â Â <span class="k">end
</span></div>
</pre>
<p>Since my adapter only needs to read data, I just had to implement #read_one and #read_many. I implemented a #read private method accessed by #read_one and #read_many as you can see <a title="implementation" href="http://github.com/mattetti/dm-gvideo-adapter/tree/master/lib/dm-gvideo-adapter.rb#L29-60" target="_blank">here</a>.</p>
<p>Because DM offers a clean and consistent API, things were pretty easy and you can check the <a title="specs" href="http://github.com/mattetti/dm-gvideo-adapter/tree/master/spec/dm-gvideo-adapter_spec.rb" target="_blank">specs</a> to have a better understanding of how things are expected to work.</p>
<p>As you can see with less than 80LOC, I implemented an adapter that I can use and reuse cleanly in my apps. And on top of that, the adapter uses a standard API known by everyone using DM.</p>
<p><strong>Even though, this adapter has a very limited scope, I hope this example will inspire you and at your turn, will write some more cool adapters to share with the rest of us.</strong></p>
<h2>UPDATE:</h2>
<p>Sam Smoot, also known as Mr DataMapper made a very good comment. I should explain a bit more how you create a collection of objects to return when a user does a .all or .first call.</p>
<p>The whole collection creation is a bit strange at first.</p>
<p>In my read method, &#8220;set&#8221; is a DataMapper::Collection instance that is passed by the #read_one or #read_many method.</p>
<p>The collection needs to be loaded with an array of ordered params.</p>
<p>For instance in this case, to create a Video collection I need to load the collection with an ordered array of params like docid, title etc..Â  However, some params might be lazy loaded and in some instance, the query might be in the form of Video.all(:fields =&gt; :title)</p>
<p>To figure out what fields/params we need, I used:</p>
<pre><span class="n">properties</span> <span class="o">=</span> <span class="n">query</span><span class="o">.</span><span class="n">fields
</span></pre>
<p>Which retrieves the required fields. Once you have the fields you need to return the structured data and that&#8217;s when I used the #result_values method which basically loop through the fields and retrieves the data by sending the param as a method to the result:</p>
<pre><span class="n">properties</span><span class="o">.</span><span class="n">map</span> <span class="p">{</span> <span class="o">|</span><span class="nb">p</span><span class="o">|</span> <span class="n">result</span><span class="o">.</span><span class="n">send</span><span class="p">(</span><span class="nb">p</span><span class="o">.</span><span class="n">field</span><span class="p">(</span><span class="n">repository_name</span><span class="p">))</span> <span class="p">}</span></pre>
<p>The values once retrieved get loaded, but here is a trick I took from wycat&#8217;s saleforce API:</p>
<pre><span class="n">arr</span> <span class="p">?</span> <span class="n">set</span><span class="o">.</span><span class="n">load</span><span class="p">(</span><span class="n">values</span><span class="p">)</span> <span class="p">:</span> <span class="p">(</span><span class="k">break</span> <span class="n">set</span><span class="o">.</span><span class="n">load</span><span class="p">(</span><span class="n">values</span><span class="p">,</span> <span class="n">query</span><span class="p">))
</span></pre>
<p>This snippet is quite simple if we set arr as true, that means we want to return an array so we will keep on looping (used by read_more when we want to return an array of objects). Otherwise we use the break operator which will stop the loop but also return a value. (yes, Ruby is awesome). By returning a single object we do exactly what&#8217;s expected and don&#8217;t have to call #first on a returned array. Pretty slick</p>
]]></content:encoded>
			<wfw:commentRss>http://merbist.com/2008/09/29/write-your-own-custom-datamapper-adapter/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Deploying a bundled merb app (merb 0.9.7+)</title>
		<link>http://merbist.com/2008/09/23/deploying-a-bundled-merb-app-merb-097/</link>
		<comments>http://merbist.com/2008/09/23/deploying-a-bundled-merb-app-merb-097/#comments</comments>
		<pubDate>Tue, 23 Sep 2008 23:32:41 +0000</pubDate>
		<dc:creator>Matt Aimonetti</dc:creator>
				<category><![CDATA[Tutorial]]></category>
		<category><![CDATA[bundle]]></category>
		<category><![CDATA[capistrano]]></category>
		<category><![CDATA[deployment]]></category>
		<category><![CDATA[freezer]]></category>
		<category><![CDATA[merb]]></category>
		<category><![CDATA[ruby]]></category>

		<guid isPermaLink="false">http://merbist.com/?p=23</guid>
		<description><![CDATA[Since Merb 0.9.7 the Merb team decided to change the way you can bundle an app. Until 0.9.7 you would use the merb-freezer plugin which was supporting git submodules and gems. The only problem was that you still had to install merb-freezer on your server and it had to stay in sync with your app&#8230; [...]]]></description>
			<content:encoded><![CDATA[<p>Since Merb 0.9.7 the Merb team decided to change the way you can bundle an app. Until 0.9.7 you would use the merb-freezer plugin which was supporting git submodules and gems. The only problem was that you still had to install merb-freezer on your server and it had to stay in sync with your app&#8230; kinda lame <img src='http://merbist.com/wp-includes/images/smilies/icon_sad.gif' alt=':(' class='wp-smiley' /> </p>
<div class="wp-caption alignleft" style="width: 250px"><a href="http://flickr.com/photos/vieuxbandit/1987820964/" target="_blank"><img class="illustration" title="Ginger" src="http://farm3.static.flickr.com/2373/1987820964_bc54df0d81_m.jpg" alt="Ginger" width="240" height="180" /></a><p class="wp-caption-text">Ginger roots, great for deployment issues</p></div>
<p>Instead, after a lot of discussions, we decided to add this feature to merb-core and let you bundle all your dependencies in a bundled gem folder. No more support for git submodules as they are hard to keep track of and don&#8217;t handle dependencies very well (not at all).</p>
<p>The new freezing strategy is very well described in <a title="merbunity article about bundling a Merb app" href="http://merbunity.com/tutorials/18" target="_blank">this merbunity article</a>. However it doesn&#8217;t really explain how to deploy a bundled app.</p>
<p>So let&#8217;s imagine for a second that we bundle our app, generated the scripts needed to start merb/rake etc&#8230;</p>
<p><span id="more-23"></span></p>
<p>The key thing to do is to have a decent deployment recipe. Let&#8217;s look at my cap recipe:</p>
<div class="code"><script src="http://gist.github.com/12432.js"></script></div>
<p>As you can see there are few key elements:</p>
<ul>
<li>recompile native gems for the web server</li>
<li>call bin/merb and not merb directly</li>
</ul>
<p>One thing you need to be aware of is that your bundled gems need to be up to date and play well alone. When you test your bundled app locally, you might endup loading system wide gems available which you don&#8217;t have on your deployment server.</p>
<p>If when you deploy your app everything seems fine but you can&#8217;t access your app, check that you are recompiling native gems during your deployment and make sure you have bundled all the deps you need and that they work well alone.</p>
<p>One more advise, if you can&#8217;t figure out what&#8217;s going, try ssh&#8217;ing to your server, go to your current folder and try bin/merb -iÂ  to see what&#8217;s going on.</p>
]]></content:encoded>
			<wfw:commentRss>http://merbist.com/2008/09/23/deploying-a-bundled-merb-app-merb-097/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
	</channel>
</rss>

