<?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>Sergio Veiga</title>
	<atom:link href="http://sergioveiga.com/index.php/feed/" rel="self" type="application/rss+xml" />
	<link>http://sergioveiga.com</link>
	<description></description>
	<lastBuildDate>Sun, 21 Feb 2010 05:02:03 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.5</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Erlang Code to UnShort Tiny Url&#8217;s</title>
		<link>http://sergioveiga.com/index.php/2010/02/21/erlang-code-to-unshort-urls/</link>
		<comments>http://sergioveiga.com/index.php/2010/02/21/erlang-code-to-unshort-urls/#comments</comments>
		<pubDate>Sun, 21 Feb 2010 04:57:22 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://sergioveiga.com/?p=150</guid>
		<description><![CDATA[A simple erlang gen_server to return original url from short ones.
It accepts any kind of of url, retrieving zero or one redirect location.
Just copy the code and give it a test :
darkua:~ sergioveiga$ erl
Erlang R13B03 (erts-5.7.4) [source] [smp:2:2] [rq:2] [async-threads:0] [kernel-poll:false]
Eshell V5.7.4  (abort with ^G)
1> c(unshort_srv).
{ok,unshort_srv}
2> unshort_srv:start_link().
{ok,}
3> unshort_srv:unshort(&#8221;http://tarpipe.com/kE&#8221;).
{ok,&#8221;http://sergioveiga.com/index.php/2010/02/21/erlang-code-to-unshort-urls/&#8221;}
4> unshort_srv:unshort(&#8221;http://google.com&#8221;).
{ok,&#8221;http://www.google.com/&#8221;}
5>
&#160;Share now!]]></description>
			<content:encoded><![CDATA[<p>A simple erlang gen_server to return original url from short ones.</p>
<p>It accepts any kind of of url, retrieving zero or one redirect location.</p>
<script src="http://gist.github.com/310121.js"></script>
<p>Just copy the code and give it a test :</p>
<p>darkua:~ sergioveiga$ erl<br />
Erlang R13B03 (erts-5.7.4) [source] [smp:2:2] [rq:2] [async-threads:0] [kernel-poll:false]</p>
<p>Eshell V5.7.4  (abort with ^G)<br />
1> c(unshort_srv).<br />
{ok,unshort_srv}<br />
2> unshort_srv:start_link().<br />
{ok,<0.39.0>}<br />
3> unshort_srv:unshort(&#8221;http://tarpipe.com/kE&#8221;).<br />
{ok,&#8221;http://sergioveiga.com/index.php/2010/02/21/erlang-code-to-unshort-urls/&#8221;}<br />
4> unshort_srv:unshort(&#8221;http://google.com&#8221;).<br />
{ok,&#8221;http://www.google.com/&#8221;}<br />
5></p>
<p style="white-space:nowrap"><img style="border:0px" src="http://tarpipe.com/img/tarpipe.png" />&nbsp;<a target="_blank" href="http://tarpipe.com/share/?t=Erlang+Code+to+UnShort+Tiny+Url%E2%80%99s&u=http%3A%2F%2Fsergioveiga.com%2Findex.php%2F2010%2F02%2F21%2Ferlang-code-to-unshort-urls%2F&b=Reading %22Erlang+Code+to+UnShort+Tiny+Url%E2%80%99s%22">Share now!</a></p>]]></content:encoded>
			<wfw:commentRss>http://sergioveiga.com/index.php/2010/02/21/erlang-code-to-unshort-urls/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Erlang kicks C++ ass</title>
		<link>http://sergioveiga.com/index.php/2009/12/28/erlang-kicks-c-ass/</link>
		<comments>http://sergioveiga.com/index.php/2009/12/28/erlang-kicks-c-ass/#comments</comments>
		<pubDate>Mon, 28 Dec 2009 17:39:31 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[erlang]]></category>

		<guid isPermaLink="false">http://sergioveiga.com/?p=145</guid>
		<description><![CDATA[I just read a paper from Ericsson about Productivity and Quality, where they compare Erlang and C++, and guess what&#8230; erlang rules with 4 to 10 times less code and less errors!!! You can read the full paper here, but i copy paste some of the conclusions :
&#8220;Comparisons between Ericsson-internal development projects indicate similar line/hour
productivity, [...]]]></description>
			<content:encoded><![CDATA[<p>I just read a paper from Ericsson about Productivity and Quality, where they compare Erlang and C++, and guess what&#8230; erlang rules with 4 to 10 times less code and less errors!!! You can read the full paper <a href="http://www.erlang.se/publications/Ulf_Wiger.pdf">here</a>, but i copy paste some of the conclusions :</p>
<p><em>&#8220;Comparisons between Ericsson-internal development projects indicate similar line/hour<br />
productivity, including all phases of software development, rather independently of which<br />
language (Erlang, PLEX, C, C++ or Java) was used. What differentiates the different<br />
languages then becomes source code volume. </em></p>
<p><em><br />
Some concrete comparisons of source code volume have been made, as applications<br />
written in C++ have been rewritten in Erlang, resulting in a ten-fold reduction in the<br />
number of lines of uncommented source code. Other comparisons have indicated a four-<br />
fold reduction. A reasonable conclusion is that productivity increases by the same factor,<br />
given the same line/hour programmer productivity.<br />
</em></p>
<p><em>When measuring product quality in number of reported errors per 1000 lines of source<br />
code, the same relationship seems to exist: similar error density, but given the difference<br />
in code volume, roughly 4-10 times fewer errors in Erlang-based products.<br />
Furthermore, experiences from maintaining some Erlang-based products in the field<br />
indicates that error corrections usually do not give rise to unwanted side-effects. This is in<br />
line with what one would expect from using a mostly side-effect free declarative<br />
language.<br />
</em></p>
<p><em>These comparisons do not pretend to hold up to scientific scrutiny, but they are collected<br />
from indicators which show a rather consistent pattern. They also seem consistent with<br />
opinions offered by non-Ericsson developers [one2one],[sendmail].<br />
While AXD 301 consists of programs written in C, C++ and Java as well as Erlang, and<br />
each language is used where it fits best, practically all the complex work is done in<br />
Erlang. This is usually decided by the designers themselves – many of our most skilled C<br />
programmers prefer Erlang for complex tasks, and consider it the obvious choice for<br />
anything that involves concurrency or distribution.<br />
</em></p>
<p><em>Finally, we have seen that programmers – even those with no previous exposure to<br />
functional languages – learn Erlang quickly, and become productive within a matter of<br />
weeks.&#8221;</em></p>
<p>I had exactly the same feeling when started to code erlang comparing to my previous most used languages, Java and  PHP.</p>
<p style="white-space:nowrap"><img style="border:0px" src="http://tarpipe.com/img/tarpipe.png" />&nbsp;<a target="_blank" href="http://tarpipe.com/share/?t=Erlang+kicks+C%2B%2B+ass&u=http%3A%2F%2Fsergioveiga.com%2Findex.php%2F2009%2F12%2F28%2Ferlang-kicks-c-ass%2F&b=Reading %22Erlang+kicks+C%2B%2B+ass%22">Share now!</a></p>]]></content:encoded>
			<wfw:commentRss>http://sergioveiga.com/index.php/2009/12/28/erlang-kicks-c-ass/feed/</wfw:commentRss>
		<slash:comments>16</slash:comments>
		</item>
		<item>
		<title>Idea 73</title>
		<link>http://sergioveiga.com/index.php/2009/12/17/idea-73/</link>
		<comments>http://sergioveiga.com/index.php/2009/12/17/idea-73/#comments</comments>
		<pubDate>Thu, 17 Dec 2009 18:55:15 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[erlang]]></category>

		<guid isPermaLink="false">http://sergioveiga.com/?p=143</guid>
		<description><![CDATA[Twiiter Im : the idea is transform twitter social relations, into a Distributed Instant Message Network. In other words, we could build something close to facebook chat system, that works in any website by just inserting a simple js script. So you would be able to see what friends are current online, and engage deeper [...]]]></description>
			<content:encoded><![CDATA[<p>Twiiter Im : the idea is transform twitter social relations, into a Distributed Instant Message Network. In other words, we could build something close to facebook chat system, that works in any website by just inserting a simple js script. So you would be able to see what friends are current online, and engage deeper discussions that are not possible in 140 chars.</p>
<p>So mainly its similar to meebo/mashable integration, but without needing to register in any place, and much more simpler.</p>
<p>The best part of this idea, to me, is that would be a great project to push erlang to the max <img src='http://sergioveiga.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>What you think?</p>
<p style="white-space:nowrap"><img style="border:0px" src="http://tarpipe.com/img/tarpipe.png" />&nbsp;<a target="_blank" href="http://tarpipe.com/share/?t=Idea+73&u=http%3A%2F%2Fsergioveiga.com%2Findex.php%2F2009%2F12%2F17%2Fidea-73%2F&b=Reading %22Idea+73%22">Share now!</a></p>]]></content:encoded>
			<wfw:commentRss>http://sergioveiga.com/index.php/2009/12/17/idea-73/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Erlang Web Development with Nitrogen</title>
		<link>http://sergioveiga.com/index.php/2009/12/03/erlang-web-development-with-nitrogen/</link>
		<comments>http://sergioveiga.com/index.php/2009/12/03/erlang-web-development-with-nitrogen/#comments</comments>
		<pubDate>Thu, 03 Dec 2009 15:49:17 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[erlang]]></category>
		<category><![CDATA[nitrogen]]></category>

		<guid isPermaLink="false">http://sergioveiga.com/?p=129</guid>
		<description><![CDATA[I willl be presenting @codebits tomorrow by 11am in stage 1, my Erlang On Nitro talk.
It will be a simple introduction to erlang, and how you can use it for building web applications. With erlang and nitrogen you can very easily start building real-time web applications, using comet, that are fault-tolerant. I will assume that [...]]]></description>
			<content:encoded><![CDATA[<p>I willl be presenting @<a href="http://codebits.eu/">codebits</a> tomorrow by 11am in stage 1, my <a href="http://codebits.eu/intra/s/session/89">Erlang On Nitro</a> talk.</p>
<p>It will be a simple introduction to erlang, and how you can use it for building web applications. With erlang and nitrogen you can very easily start building real-time web applications, using comet, that are fault-tolerant. I will assume that you have never heard of erlang before, so don&#8217;t be afraid to join us.</p>
<p>The talk will follow the <a href="http://sergioveiga.com/index.php/2009/12/02/erlang-on-nitro-erlang-web-development-tutorial-part-13/">tutorial</a> i published some hours ago <img src='http://sergioveiga.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  , so i you are attending i suggest a quick read, in order to make the talk more productive!</p>
<p style="white-space:nowrap"><img style="border:0px" src="http://tarpipe.com/img/tarpipe.png" />&nbsp;<a target="_blank" href="http://tarpipe.com/share/?t=Erlang+Web+Development+with+Nitrogen&u=http%3A%2F%2Fsergioveiga.com%2Findex.php%2F2009%2F12%2F03%2Ferlang-web-development-with-nitrogen%2F&b=Reading %22Erlang+Web+Development+with+Nitrogen%22">Share now!</a></p>]]></content:encoded>
			<wfw:commentRss>http://sergioveiga.com/index.php/2009/12/03/erlang-web-development-with-nitrogen/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Erlang On Nitro &#8211; Erlang Web Development Tutorial &#8211; Part 3/3</title>
		<link>http://sergioveiga.com/index.php/2009/12/03/erlang-on-nitro-erlang-web-development-tutorial-part-33/</link>
		<comments>http://sergioveiga.com/index.php/2009/12/03/erlang-on-nitro-erlang-web-development-tutorial-part-33/#comments</comments>
		<pubDate>Thu, 03 Dec 2009 15:32:23 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[erlang]]></category>
		<category><![CDATA[nitrogen]]></category>

		<guid isPermaLink="false">http://sergioveiga.com/?p=117</guid>
		<description><![CDATA[So now you that know already how to start developing your web projects using erlang, i want to present to you a resume of tools, tips, applications and some erlang resources that will make your life easier.
Tools &#38; Tips
Toolbar : a very simple visual toolbar for the most used tools in erlang. Type on your [...]]]></description>
			<content:encoded><![CDATA[<p>So now you that know already how to start developing your web projects using erlang, i want to present to you a resume of tools, tips, applications and some erlang resources that will make your life easier.</p>
<h2>Tools &amp; Tips</h2>
<p><strong>Toolbar</strong> : a very simple visual toolbar for the most used tools in erlang. Type on your erlang shell toolbar:start(). You should see 4 icons representing this tools:</p>
<ul>
<li><strong>Table Viewer:</strong> An ETS and MNESIA graphical table visualizer. With this you can view and change data inside a ets or mnesia table. On shell you can call it using tv:start().</li>
</ul>
<p><a href="http://img.skitch.com/20091202-nfyejf2hnsuf5qgda916ci74m.jpg"><img class="alignnone" src="http://img.skitch.com/20091202-nfyejf2hnsuf5qgda916ci74m.jpg" alt="" width="505" height="269" /></a></p>
<ul>
<li><strong>Process Manager</strong> : A process manager used to inspect the state of an Erlang system. Call on erlang shell : pman:start(). X11 window will open showing the running processes for this node.</li>
</ul>
<p><a href="http://img.skitch.com/20091203-tahd1bid96sbdk2ajaj8mfgnc5.jpg"><img class="alignnone" src="http://img.skitch.com/20091203-tahd1bid96sbdk2ajaj8mfgnc5.jpg" alt="" width="512" height="282" /></a></p>
<ul>
<li><strong>Debugger</strong> : A debugger for debugging and testing of Erlang programs. Call on erlang shell : debugger:start(). A window will open like this one</li>
</ul>
<p><a href="http://img.skitch.com/20091202-m68ie1tk7etyew2cr3tth6a2fc.jpg"><img class="alignnone" src="http://img.skitch.com/20091202-m68ie1tk7etyew2cr3tth6a2fc.jpg" alt="" width="514" height="403" /></a></p>
<ul>
<li><strong>Application Monito</strong>r : A utility used to supervise Applications executing on several Erlang nodes. Very useful when you start deploying cluster of application in different nodes <img src='http://sergioveiga.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  On shell use appmon:start().</li>
</ul>
<p><a href="http://img.skitch.com/20091202-bw1t96316418qfkhbxpkr1tx58.jpg"><img class="alignnone" src="http://img.skitch.com/20091202-bw1t96316418qfkhbxpkr1tx58.jpg" alt="" width="517" height="564" /></a></p>
<p>Some other useful tips:</p>
<p><strong>Tip1 :</strong> if you have no internet to search, you can use erlang manual. Just type this in your terminal</p>
<pre>erl -man lists</pre>
<p><strong>Tip2</strong> : in order to let an application running in background, all you need is to add this to your start script</p>
<pre>-detached \</pre>
<p><strong>Tip3</strong> : you probably have notice that we are using error_logger module. This is the best way to deal with errors, and for example get warned by email each time your application is in trouble. Please read more <a href="http://www3.erlang.org/documentation/doc-5.4.2.1/lib/kernel-2.10.2/doc/html/error_logger.html">here</a></p>
<h2>Applications</h2>
<p>As you probably noticed i did not talk about any data-store mechanisms, in order to avoid to much detail. In erlang there are many options to store data. Erlang has two system modules ets and dets that are used for efﬁcient storage of large numbers of Erlang terms. <strong>ETS</strong> is short for Erlang term storage,<br />
and <strong>DETS</strong> is short for disk ets. ETS and DETS perform basically the same task: they provide large key-value lookup tables. ETS is memory resident, while DETS is disk resident. You can use ETS or DETS directly or you can use erlang database : <strong>MNESIA</strong>, a distributed DataBase Management System, with a relational/object hybrid data model. Mnesia is really cool because it maps directly to records, and you have a nice query language to it.</p>
<p>Another great way to store info in erlang is using one of the coolest erlang projects: <a href="http://couchdb.apache.org/">couchdb</a> is a document-oriented database that can be queried and indexed in a MapReduce fashion using JavaScript. In other words you don&#8217;t need a schema to your data, and since its json its very easy to write/read. This is very useful for example when you are saving 3rd party data that you don&#8217;t control, like tweets. In order to make the interaction between erlang and couchdb or any other service, before you start coding, look first at github (another great project using erlang), where you can find a lot erlang code, that will make you life even easier.</p>
<h2>Some useful Erlang Resources</h2>
<p>You can find a lot of stuff on the web about erlang, but here are some of our favorite bookmarks about erlang :</p>
<ul>
<li><a href="http://erlang.org/doc/man/">http://erlang.org/doc/man/</a></li>
<li><a href="http://nitrogenproject.com/">http://nitrogenproject.com/</a></li>
<li><a href="http://trapexit.org/">http://trapexit.org/</a></li>
<li><a href="http://www.planeterlang.org/">http://www.planeterlang.org/</a></li>
<li><a href="http://blog.socklabs.com/">http://blog.socklabs.com/</a></li>
<li><a href="http://yarivsblog.com/">http://yarivsblog.com/</a></li>
<li><a href="http://spawnlink.com/">http://spawnlink.com/</a></li>
<li><a href="http://medevyoujane.com/">http://medevyoujane.com/</a></li>
<li><a href="http://metajack.im/">http://metajack.im/</a></li>
<li><a href="http://anders.conbere.org/blog/">http://anders.conbere.org/blog/</a></li>
<li><a href="http://kungfooguru.wordpress.com/">http://kungfooguru.wordpress.com/</a></li>
<li><a href="http://beebole.com/erlang/en/">http://beebole.com/erlang/en/</a></li>
<li><a href="http://erlanganswers.com/web/mcedemo">http://erlanganswers.com/web/mcedemo</a></li>
<li><a href="http://schemecookbook.org/Erlang/AllRecipes">http://schemecookbook.org/Erlang/AllRecipes</a></li>
<li><a href="http://www.undefined.org/c4-1/slides/slides.html">http://www.undefined.org/c4-1/slides/slides.html</a></li>
<li><a href="http://jeremy.marzhillstudios.com/">http://jeremy.marzhillstudios.com/</a></li>
<li><a href="http://www.infoq.com/presentations/Systems-that-Never-Stop-Joe-Armstrong">http://www.infoq.com/presentations/Systems-that-Never-Stop-Joe-Armstrong</a></li>
</ul>
<h2>Resume</h2>
<p>Erlang it has been around for a long time now, but the buzz around erlang started around 2007 with the publication of Programming Erlang: <a href="http://pragprog.com/titles/jaerlang/programming-erlang">Software for a Concurrent World by Joe Armstrong</a>, erlang creator and the use of erlang in really projects, like ejabberd, couchdb or facebook chat system. With this buzz erlang community start to grow outside the Telecom world specially in the web world.</p>
<p>Erlang is not just another programming language,  for me that have been programming more then 5 years with OO, its new paradigm, a new way to think, a new form of coding. And we are deeply in love with it&#8230; we hope you come to.</p>
<p>If you are not yet sold, just watch <a href="http://www.youtube.com/watch?v=uKfKtXYLG78">erlang demo video from the 80&#8217;s</a> and you will for sure <img src='http://sergioveiga.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p style="white-space:nowrap"><img style="border:0px" src="http://tarpipe.com/img/tarpipe.png" />&nbsp;<a target="_blank" href="http://tarpipe.com/share/?t=Erlang+On+Nitro+%E2%80%93+Erlang+Web+Development+Tutorial+%E2%80%93+Part+3%2F3&u=http%3A%2F%2Fsergioveiga.com%2Findex.php%2F2009%2F12%2F03%2Ferlang-on-nitro-erlang-web-development-tutorial-part-33%2F&b=Reading %22Erlang+On+Nitro+%E2%80%93+Erlang+Web+Development+Tutorial+%E2%80%93+Part+3%2F3%22">Share now!</a></p>]]></content:encoded>
			<wfw:commentRss>http://sergioveiga.com/index.php/2009/12/03/erlang-on-nitro-erlang-web-development-tutorial-part-33/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Erlang On Nitro &#8211; Erlang Web Development Tutorial &#8211; Part 2/3</title>
		<link>http://sergioveiga.com/index.php/2009/12/03/erlang-on-nitro-erlang-web-development-tutorial-part-23/</link>
		<comments>http://sergioveiga.com/index.php/2009/12/03/erlang-on-nitro-erlang-web-development-tutorial-part-23/#comments</comments>
		<pubDate>Thu, 03 Dec 2009 04:14:59 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://sergioveiga.com/?p=106</guid>
		<description><![CDATA[So now that you have already know nitrogen basics in part 1 of this tutorial, lets see what he can real do with it. So lets see a real simple web application that will track a keyword and wait for twitter to push &#8220;tweets&#8221; that contains this keyword, and stream them in a never ending [...]]]></description>
			<content:encoded><![CDATA[<p>So now that you have already know nitrogen basics in part 1 of this tutorial, lets see what he can real do with it. So lets see a real simple web application that will track a keyword and wait for twitter to push &#8220;tweets&#8221; that contains this keyword, and stream them in a never ending stream. So lets grab our code :</p>
<p>Clone this <a href="http://github.com/darkua/ErlanOnNitro_TwitterStream">git repositorium</a> :</p>
<pre>darkua:~ sergioveiga$ git clone git://github.com/darkua/ErlanOnNitro_TwitterStream.git
Initialized empty Git repository in /Users/sergioveiga/ErlanOnNitro_TwitterStream/.git/
remote: Counting objects: 72, done.
remote: Compressing objects: 100% (68/68), done.
remote: Total 72 (delta 4), reused 0 (delta 0)
Receiving objects: 100% (72/72), 144.83 KiB | 182 KiB/s, done.
Resolving deltas: 100% (4/4), done.
darkua:~ sergioveiga$ cd ErlanOnNitro_TwitterStream
darkua:ErlanOnNitro_TwitterStream sergioveiga$ ./start.sh</pre>
<p><strong>NOTE : </strong>in this project we will be use a lib packed with mochiweb project, so please check if already you have mochiweb intalled. (say thanks to <a rel="nofollow" target="_blank" href="http://twitter.com/bpedro">@bpedro</a>, for pointing this out <img src='http://sergioveiga.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  )</p>
<pre>twitter_stream@localhost)4&gt; mochijson2:encode(&lt;&lt;"hello"&gt;&gt;).
[34,&lt;&lt;"hello"&gt;&gt;,34]</pre>
<p>if you don&#8217;t see this, you need to install mochiweb first. Its very easy:</p>
<pre>darkua:twitterstream sergioveiga$ echo $ERL_LIBS
/opt/local/lib/erlang/lib/:/usr/lib/erlang/lib/:/Users/sergioveiga/erlangProjects/tedi
darkua:twitterstream sergioveiga$ cd /opt/local/lib/erlang/lib/
darkua:lib sergioveiga$ sudo svn checkout http://mochiweb.googlecode.com/svn/trunk/ mochiweb-read-only
darkua:lib sergioveiga$ cd mochiweb-read-only/
darkua:mochiweb-read-only sergioveiga$ make</pre>
<p>Now you probably need to kill erlang shell, just hit ctr-c twice. Start it again and now mochijson should already be available.</p>
<p>Before you go and check your browser you need to enter your twitter credentials, needed for twitter stream. So please go to include/include.hrl and add your own credentials, and compile the project.</p>
<p>Make sure you dont any other server running on port 8000, and go to your browser http://localhost:8000/. Here you will find some descriptions and links to both examples we will follow in this part.</p>
<p>Now choose you favorite IDE, we are using textmate, and open the project dir.</p>
<p>So this is ver similar with your previous nitrogen project, with some little changes. Open your project app file inside ebin dir. Here we have added templateroot so we can put all templates inside a different directory.</p>
<p>We have created an include dir, where we will put all our include files, and on src, we divide the pages, from the libs, that will hold &#8220;hard-core&#8221; code.</p>
<h2>Example 1 &#8211; Twitter Stream</h2>
<p>A screenshot of how twitter stream looks like :</p>
<p><a href="http://img.skitch.com/20091203-xe8bgq557gykk1yc48gtcnbye8.jpg"><img class="alignnone" src="http://img.skitch.com/20091203-xe8bgq557gykk1yc48gtcnbye8.jpg" alt="" width="505" height="447" /></a></p>
<p>Now open /src/pages/web_index.erl. You can see that we almost don&#8217;t do nothing here, because this is a static file, so we are only are adding the page title, and saying witch template will be used to render the page. All the code you can see its on index.html template file.</p>
<p>Now open web_stream page.</p>
<p>Lets check body function</p>
<pre>body() -&gt;

 %%builds the stream
 Stream = start_stream(),

 %% the html to render
 Body= [
 #panel{class="header", body=[
 #h1{text="Erlang on Nitro - Twitter Stream"},
 #panel{id=feedback,class="feedback", body=[
 "Calling Twitter...pls wait..."
 ]},
 #panel{id=control,body=[#button{text="Stop", postback={stop,Stream}}]}
 ]},
 #panel{id=stream,body=[]}
 ],

 wf:render(Body).</pre>
<p>Here we are calling stream_start() to open stream connections and building the page html structure. Now check the start_stream() to see where is the magic.</p>
<pre>start_stream()-&gt;
 Pid = wf:comet(fun()-&gt; ?MODULE:loop() end),</pre>
<pre>%%check for track
 case wf:get_path_info() of
 []-&gt;
 twitter_stream:sample(Pid);
 Track-&gt;
 twitter_stream:track(Track,Pid)
 end.</pre>
<p>When calling wf:comet, we are building a comet connection to this page, and passing what function will be used to &#8220;comunicate&#8221; with the browser. Then we use wf:get_path_info() to get extra info on path, that we will use to call twitter, for example the twitter or hello keyword from the examples. All the connection to twitter stream api happens inside twitter_stream, and for now you can look at it as a black box that streams tweets for you, later you can check it out and try to understand what is happening.</p>
<p>Now before checking loop function, its time to better undersand one of erlang top features, creating and communicating with processes. When we did wf:comet, what is happening in resume, is that we have spawned loop function into a new process, and now we can comunicate with it by sending to the Process Id messages. And to do that we just need to do this :</p>
<pre>Pid ! message</pre>
<p>In order to put a process waiting for messages is also very simple, just do this :</p>
<pre>receive
 Message-&gt;
 ...
 end.</pre>
<p>When creating a receive block, you are telling erlang to wait there until he receives a new message, that he will try to match to execute the respective code.</p>
<p>Now lets check a very simple example in order to better understand this. Open file spawn_example inside libs. You can see that we just have 2 functions, start and loop. On start we are spawning function loop, and registering the process with a name to be easier to call them after, like your fathers did with you <img src='http://sergioveiga.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>Now go to erlang shell and call this:</p>
<pre>(twitter_stream@localhost)2&gt; spawn_example:start().
true
(twitter_stream@localhost)3&gt; bot ! hello.
Hello. How are you?
hello
(twitter_stream@localhost)4&gt;</pre>
<p>Very simple and cool, but now try to call it again</p>
<pre>(twitter_stream@localhost)15&gt; bot ! hello.
** exception error: bad argument
 in operator  !/2
 called as bot ! hello
(twitter_stream@localhost)16&gt;</pre>
<p>Humm&#8230; the reason it failed its very simple. After the process received the first message he executed the code matched to hello and it ended. So when you try to send a new message to it, it no longer exists, and it fails. So if you want to create process that after processing a message continues waiting for other you need to recall the function. So in the end of the loop add a call to loop.</p>
<pre>loop()-&gt;
 receive
 hello -&gt;
 io:format("Hello. How are you?~n",[]);
 _-&gt;
 void
 end,
 loop().</pre>
<p>Now lets try again</p>
<pre>(twitter_stream@localhost)16&gt; sync:go().
Recompile: ./src/libs/spawn_example
ok
(twitter_stream@localhost)17&gt; spawn_example:start().
true
(twitter_stream@localhost)18&gt; bot ! hello.
Hello. How are you?
hello
(twitter_stream@localhost)19&gt; bot ! hello.
Hello. How are you?
hello</pre>
<p>As you can see now the process no longer dies. Now lets see another great feature of erlang: hot code swapping, the ability to change the code without stopping the system. Try to change the text on the message, for example to:</p>
<pre>io:format("Hot swapping rocks!~n",[])</pre>
<p>sync:go and lets see what happens:</p>
<pre>(twitter_stream@localhost)24&gt; sync:go().
Recompile: ./src/libs/spawn_example
ok
(twitter_stream@localhost)25&gt; bot ! hello.
Hello. How are you?
hello</pre>
<p>Humm&#8230; the old message is still there. The reason this happens is very simple. If we dont call &#8220;externally&#8221; by  prefixing the module name we are saying to erlang to “use this version of this method” and not the current version. So all we need to do is add the ?MODULE to the loop call, in the start function and also in the end of the loop. Now sync your code, and start your bot again.</p>
<pre>(twitter_stream@localhost)38&gt; sync:go().
Recompile: ./src/libs/spawn_example
ok
(twitter_stream@localhost)39&gt; spawn_example:start().
true
(twitter_stream@localhost)40&gt; bot ! hello.
Hot swapping rocks!
hello</pre>
<p>Now lets change the message again, to &#8220;Hot swapping really rocks&#8221;. Sync your code again and send him a message.</p>
<pre>(twitter_stream@localhost)41&gt; sync:go().
Recompile: ./src/libs/spawn_example
ok
(twitter_stream@localhost)42&gt; bot ! hello.
Hot swapping rocks!
hello
(twitter_stream@localhost)43&gt; bot ! hello.
Hot swapping really rocks!
hello</pre>
<p>As you can see the first message the bot receives the old code will be executed, because the process was already blocked waiting for a message, but when it run again it will already be using the current version of the code. You can see final version of spawn_example <a href="http://gist.github.com/raw/247001/c912f04cc9a4faedfda62cf8043d1ede23951e7c/spawn_example">here</a>.</p>
<p>Now back to our example, you can see exactly this happening with the loop function inside web_stream module. As you can see the loop function will be waiting for a subset of messages that twitter stream will send to him, and according to each we will be doing something different. Now what is important to understand is how nitrogen communicates with the client browser.</p>
<p>We are using 2 nitrogen functions  wf:update(id, content) and wf:insert_top(id, content) that will update and insert on the top of a DOM element. Nitrogen will translate this to the corresponding javascript, using jquery lib, and send it to the browser when we call wf:comet_flush(). So only when call this function inside a comet loop, we will be sending all previous javascript code built with wf:update/wf:insert_top&#8221; as a response to the comet connection.</p>
<pre>loop()-&gt;
 receive
 {unauthorized,Message}-&gt;
 io:format("~p~n",[Message]),
 wf:update(feedback,"Your twitter credentials are wrong, check include.htr file!");
 {start,_Message}-&gt;
 wf:update(feedback,"Stream Running...");
 {stream,Message}-&gt;
 get_tweet_info(Message);
 {stream_end,_Message}-&gt;
 restart_button(),
 wf:update(feedback,"Stream Ended...");
 {stop,_Reason}-&gt;
 restart_button(),
 wf:update(feedback,"Stream Stoped...");
 {error,Reason}-&gt;
 error_logger:error_msg("Error : ~p~n",[Reason]),
 restart_button(),
 wf:update(feedback,#panel{class="error",body=wf:f("Error : ~s !",[Reason])});
 Any-&gt;
 error_logger:info_msg("ANY : ~p~n",[Any])
 after 55000 -&gt;
 wf:update(feedback,"to quiet for me...")
 end,
 wf:comet_flush(),
 ?MODULE:loop().</pre>
<p>With this simple code you have learn the basic blocks to create parallel computing, and the possibility to push content to users without the need to be constantly polling a service. And this is really cool because is all you need to create cool real-time / multi-user applications.</p>
<h2>Example 2 &#8211; Twitter Cloud</h2>
<p>Twitter Cloud Screenshot :</p>
<p><a href="http://img.skitch.com/20091203-rbk3krubtky9pey747chxe85b4.jpg"><img class="alignnone" src="http://img.skitch.com/20091203-rbk3krubtky9pey747chxe85b4.jpg" alt="" width="505" height="387" /></a></p>
<p>Nitrogen does already lot of work for us on erlang/javascript interaction, making easier  the creation of appealing  and rich web applications. Check web_cloud example where we have created another visualization for twitter stream, but now its a cloud of twitter users, where the size of the pictures is related to the ratio following/followers, where you can click to see the status update.</p>
<p>if you open web_cloud.erl, you can see that its very closed to web_stream, but now instead of building the html on the server we are passing the info to the the browser and will will build the dom with javascript. This can be achieved very easily with nitrogen using wf:wire constructor. As you can check on line 126 of web_cloud</p>
<pre>wf:wire(wf:f("buildTweet({id:'~s',screen_name:'~s',picture:'~s',text:\"~s\",size:'~p'})",
[Tweet#tweet.id,
Tweet#tweet.screen_name,
Tweet#tweet.picture,
wf_utils:js_escape(Tweet#tweet.text),
Tweet#tweet.size])
).</pre>
<p>Mainly we are calling the js function buildTweet that you can find on /js/main.js a js object with all the tweet function. We also use another great nitrogen function wf:f, that helps you build complex strings.</p>
<p>Another thing really useful is giving to an event different actions, like you can see in line 27.</p>
<pre>#panel{id=control,body=[#button{text="Stop", actions=#event{actions="$.growl('','Stream is Stoping...');"}, postback={stop,Stream}}]}</pre>
<p>Inside each event you can define your postback, and you can also use actions parameters to execute javascript. So if you click on the stop button, we will be calling event({stop,Stream}) and also calling jquery-growl plugin that will show a message to the user.  We can even define more than one event type to the same element. For example change control panel this on body function</p>
<pre>#panel{id=control,body=[#button{text="Stop", actions=[</pre>
<pre>#event{actions="$.growl('','Stream is Stoping...');", postback={stop,Stream}},</pre>
<pre>#event{type=mouseover,actions="$.growl('','Click if you are a mouse!...');"}]
}]}</pre>
<p>sync:go, and check your example. You should be seeing a message appear when you put your mouse over stop button and other when you click it.<br />
As you can imagine this is a very simple example of all you can do with nitrogen . So please check nitrogen project where will have a lot of <a href="http://nitrogenproject.com/web/samples">cool examples</a> ,  <a href="http://nitrogenproject.com/web/reference/api">nitrogen api</a> with all functions available, and you can check some more documentation on on <a href="http://wiki.github.com/rklophaus/nitrogen/installing-nitrogen">github wiki</a>.</p>
<p>So now you know already enough to start coding your own ideas and projects, but before read <a href="http://sergioveiga.com/index.php/2009/12/03/erlang-on-nitro-erlang-web-development-tutorial-part-33/">last part </a>of this tutorial, where we will resume some of the tools erlang has to help on your adventure.</p>
<p style="white-space:nowrap"><img style="border:0px" src="http://tarpipe.com/img/tarpipe.png" />&nbsp;<a target="_blank" href="http://tarpipe.com/share/?t=Erlang+On+Nitro+%E2%80%93+Erlang+Web+Development+Tutorial+%E2%80%93+Part+2%2F3&u=http%3A%2F%2Fsergioveiga.com%2Findex.php%2F2009%2F12%2F03%2Ferlang-on-nitro-erlang-web-development-tutorial-part-23%2F&b=Reading %22Erlang+On+Nitro+%E2%80%93+Erlang+Web+Development+Tutorial+%E2%80%93+Part+2%2F3%22">Share now!</a></p>]]></content:encoded>
			<wfw:commentRss>http://sergioveiga.com/index.php/2009/12/03/erlang-on-nitro-erlang-web-development-tutorial-part-23/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Erlang On Nitro &#8211; Erlang Web Development Tutorial &#8211; Part 1/3</title>
		<link>http://sergioveiga.com/index.php/2009/12/02/erlang-on-nitro-erlang-web-development-tutorial-part-13/</link>
		<comments>http://sergioveiga.com/index.php/2009/12/02/erlang-on-nitro-erlang-web-development-tutorial-part-13/#comments</comments>
		<pubDate>Wed, 02 Dec 2009 18:16:11 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[erlang]]></category>
		<category><![CDATA[nitrogen]]></category>

		<guid isPermaLink="false">http://sergioveiga.com/?p=61</guid>
		<description><![CDATA[After learning erlang basics, and fell in love with it, one question pop up on my mind: Erlang is with no doubt a great language, but i make my living building web applications, so how i can use erlang to build web applications?
After some searching i discover 3 Erlang Web Frameworks : Nitrogen Project, ErlyWeb [...]]]></description>
			<content:encoded><![CDATA[<p>After learning erlang basics, and fell in love with it, one question pop up on my mind: Erlang is with no doubt a great language, but i make my living building web applications, so how i can use erlang to build web applications?</p>
<p>After some searching i discover 3 Erlang Web Frameworks : <a href="http://nitrogenproject.com/"><strong>Nitrogen Project</strong></a>, <a href="http://erlyweb.org/"><strong>ErlyWeb</strong></a> and <a href="http://www.erlang-web.org/"><strong>ErlangWeb</strong></a>.  I tested the 3, and i decided to go with Nitrogen, because it had some cool examples and documentation, and it looked simple. I have spend the last 6 months building web applications using nitrogen and i could not be more pleased.</p>
<p>This tutorial is divided into 3 parts, in <a href="http://sergioveiga.com/index.php/2009/12/02/erlang-on-nitro-erlang-web-development-tutorial-part-13/">part 1</a> we will assume that you are a newbie to erlang also, so i will try to explain some basic stuff about erlang as we go, but i recommend you to read this hello world tutorials to better understand this one #link , #link &#8230;</p>
<p>In <a href="http://sergioveiga.com/index.php/2009/12/03/erlang-on-nitro-erlang-web-development-tutorial-part-23/">part 2</a> we will show in a step by step explanation how to build a simple and powerful app with erlang and nitrogen, using twitter stream api.</p>
<p>In<a href="http://sergioveiga.com/index.php/2009/12/03/erlang-on-nitro-erlang-web-development-tutorial-part-33/"> part 3</a> i will present you some erlang tools that will help you mastering erlang.</p>
<h2>Get Started with Erlang &amp; Nitrogen</h2>
<p>Nitrogen is open source project, started in November 2008 by <a rel="nofollow" target="_blank" href="http://twitter.com/rklophaus">@rklophaus</a>under MIT-LICENSE. Although its pretty stable, you should be ready to assume your risk using it on production environments.</p>
<p>All the following examples were made on Mac OS X but they should be valid to Linux and windows as well.</p>
<p>First lets check if you have erlang installed. Open a terminal and type erl, if you have an error you need to install erlang.</p>
<pre>apt-get install erlang</pre>
<p>or go <a href="http://erlang.org/download.html">here</a> to download source. If you are seeing something like this, congratulations you have already erlang installed.</p>
<pre>darkua:~ sergioveiga$ erl
Erlang R13B (erts-5.7.1) [source] [smp:2:2] [rq:2] [async-threads:0] [hipe] [kernel-poll:false]
Eshell V5.7.1  (abort with ^G)
1&gt;</pre>
<p>Now its time to install Nitrogen, what is very easy, just follow this <a href="http://wiki.github.com/rklophaus/nitrogen/installing-nitrogen">instructions</a>, In resume you just need to clone nitrogen project into a directory that is included in erlang path($ERL_LIBS).</p>
<pre>darkua:~ sergioveiga$ echo $ERL_LIBS
/opt/local/lib/erlang/lib/:/usr/lib/erlang/lib/:/Users/sergioveiga/erlangProjects/tedi
darkua:~ sergioveiga$ cd /opt/local/lib/erlang/lib/
darkua:lib sergioveiga$ git clone git://github.com/rklophaus/nitrogen.git</pre>
<p>Now lets see if everthink is ok. Enter Nitrogen directory and run this command</p>
<pre>./Quickstart/quickstart.sh</pre>
<p>Now try open your browser on <a href="http://localhost:8000/web/index">http://localhost:8000/web/index</a> , you should see a copy of nitrogen website running on local.</p>
<h2>Erlang Project Structure</h2>
<p>More or less but all erlang project have a defined structure:</p>
<address>&#8211; ebin ()</address>
<address style="padding-left: 30px;">&#8211; *.beam (code compiled)</address>
<address style="padding-left: 30px;">&#8211;  name_of_the_application.app (application resource file)</address>
<address>&#8211; include</address>
<address style="padding-left: 30px;">&#8211; *.hrl (structure descriptions to include)</address>
<address>&#8211; src</address>
<address style="padding-left: 30px;">&#8211; *.erl (source code)</address>
<p>application resource file is very important because it defines your application:</p>
<pre>{application, name_of_the_application, [
 {description,  "App descritpion"},
 { vsn, "0.0.1" },
 {mod, {name_of_the_application_app, []}},
 { applications, [ kernel, stdlib] },
 {env, [
 <span style="padding-left:30px">{platform, inets},</span>
 <span style="padding-left:30px">{port, 8000},</span>
 <span style="padding-left:30px">{session_timeout, 3600},</span>
 <span style="padding-left:30px">{sign_key, randomized},</span>
 <span style="padding-left:30px">{www_root, "./wwwroot"},</span>
 <span style="padding-left:30px">{templateroot,"./wwwroot/templates"},</span>
 <span style="padding-left:30px">{scratch_directory,'./wwwroot/scratch'}]},</span>
]}.</pre>
<p>This is an example of the app file, and you can read more about application behaviour <a href="http://www.erlang.org/doc/design_principles/applications.html#appl_res_file">here</a> In resume its the file that describes you app to erlang vm, where you define its version, its environment vars, the modules, and the applications that your app will use.</p>
<p>Nitrogen as an extra dir called wwwroot, where we will store all our static files (js, html templates, css, images,etc&#8230;)</p>
<p>Now lets create your first project, using a nitrogen script that will do most of the work for you. Check if you have already nitrogen symbolic link created.</p>
<pre>darkua:~ sergioveiga$ nitrogen
Nitrogen Web Framework.

Usage:
nitrogen create [PROJECT_NAME]  - Creates a project in a subdirectory
nitrogen page [URL]             - Create a page for URL (EXAMPLE: 'nitrogen page web/blog/post')
darkua:~ sergioveiga$</pre>
<p>if you get an error you need to create a symbolic link to the path you have previous clone nitrogen</p>
<pre>sudo ln -s $ERL_LIBS/nitrogen/support/nitrogen \ /usr/local/bin/nitrogen</pre>
<p>So now its time to create our first nitrogen project</p>
<pre> nitrogen create twitter_stream</pre>
<p>A twitter_stream directory has been created and you should see a directory structure close to the one, i described before. Now in order to see that everything is ok, just run in your shell the start script</p>
<pre> ./start.sh</pre>
<p>Now you should be able to go to <a href="http://localhost:8000/">http://localhost:8000/</a> and see you project running. If you get this error</p>
<pre>=ERROR REPORT==== 18-Nov-2009::19:25:31 ===
Failed initiating web server:
(...)
{listen,eaddrinuse}
(...)</pre>
<p>This happens because you have already a server running on the same port. You need to shut down the other service, or change port on the .app file.</p>
<p>Now that we have our infrastructure ready lets get deep into real code <img src='http://sergioveiga.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<h2>Nitrogen Workflow</h2>
<p>Open twitter_stream.erl in the source directory</p>
<p>The most important in this page is understand the erlang behaviour concept. In resume Behaviours are formalizations of common patterns. So when we say -behavior(application), erlang expects this module to behave like an application. You can read more about it <a href="http://www.erlang.org/doc/design_principles/des_princ.html#id2258984">here</a>. In this case the application behaviour just needs a start and a stop function. Now open start.sh script.</p>
<pre>echo Starting TwitterStream.
erl \
-name twitter_stream<a rel="nofollow" target="_blank" href="http://twitter.com/localhost">@localhost</a>\
-pa ./ebin -pa ./include \
-s make all \
-eval "application:start(twitter_stream)"</pre>
<p>In resume we are starting erlang vm, giving it a name, include and binary path, compiling the code, and start our application, that will execute the start method we saw on twitter_stream.erl. The rest for now its not important.  So what happens when you go to http:localhost:8000/ ?  If you check you twitter_stream.app file you will see this entries</p>
<pre>{platform, inets}
{port, 8000}</pre>
<p>This is very important because this defines what http server you are going to use, and in witch port is going to run. So nitrogen is not a web server, but it starts for you one of 3 possible web servers (inets, mochiweb, and yaws), you can read more about all of them, but for now we can use any. This also means that you dont need any other webserver (apache,etc&#8230;) to run your application <img src='http://sergioveiga.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>So when you enter the address the web server will receive the request and match it to a page. By default if you just call http://localhost:8000/ the request will be mapped to http://localhost:8000/web/index/ and this will run the web_index module inside /src/pages. So if you request /web/home it will execute the module web_home.erl inside the pages dir.<br />
In order to avid to much detail, now lets assume that this mapping /web/xpto -&gt; web_xpto.erl happens by magic <img src='http://sergioveiga.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>So now open the file web_index file.</p>
<pre>-module (web_index).
-include_lib ("nitrogen/include/wf.inc").
-compile(export_all).

main() -&gt;
#template { file="./wwwroot/template.html"}.

title() -&gt;
"web_index".

body() -&gt;
#label{text="web_index body."}.

event(_) -&gt; ok.</pre>
<p><strong>-module (web_index).</strong><br />
The module definition is always required, and it defines your module name. Very important Reminder : erlang does not have namespaces, so try to use always prefixes on your own modules to avoid conflicts. For example dont call your module lists.erl&#8230; use for example my_lists.erl.. don&#8217;t laugh this happens to the best <img src='http://sergioveiga.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p><strong> -include_lib (&#8221;nitrogen/include/wf.inc&#8221;).</strong><br />
The way you can include a lib, in this case nitrogen lib, so you can use nitrogen stuff. Just keep it <img src='http://sergioveiga.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p><strong>-compile(export_all)</strong><br />
In order to call a function from module, you need to export it. To avoid that you can use this directive, but use it with caution, its best to export each one, like this:<br />
<strong> -export([ main/0, body/0, title/0, event/0]).</strong></p>
<p>So module, include, and exports is what we can call the &#8220;header&#8221; of the module. Bellow is where the code really begins <img src='http://sergioveiga.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<pre>main() -&gt;
#template { file="./wwwroot/template.html"}.</pre>
<p>This function is needed in all your pages because its the one that will be executed when you request this page. This function needs to return (in erlang return is always the last line of execution) a #template element. In erlang we have a structure called record, read more <a href="http://www.erlang.org/doc/reference_manual/records.html">here</a>, and its similar to a struct in C. This records are used by nitrogen to create elements that will help you build web applications with erlang. The template element will define the html template for this page, and the file attribute is the location of your html page that will be used as template.</p>
<p>Open wwwroot/template.html.</p>
<p>As you can see its a perfect normal html page, with some weird stuff [[[page:title()]]] on it. As you probably are imagining right now, nitrogen will parse this page, and will replace the [[[page:title()]]] with the output of the title function inside web_index. The reason to use page, and not web_index is that you can use a template for many pages, and this way it will execute the title of each calling page.</p>
<p>The other important part is the [[[script]]] element. This is where nitrogen will put all javascript he creates. Just don&#8217;t remove it or you will get into troubles <img src='http://sergioveiga.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>Now back to web_index page, you can see that title function return a simple string, and body uses another nitrogen element.  So mainly you have an element  for  all html elements (div, li, table,input&#8230;). The only problem is that nitrogen does not use always the same tags you find in html, so for example a span is #span element, but a div is #panel element&#8230; but don&#8217;t worry after a while you get use to it.</p>
<p>So lets try replace the body with this code:</p>
<pre>body()-&gt;
#textbox{text="some text"},
#button{text="Hello!"}.</pre>
<p>now go to erlang shell you have started the project and execute sync:go().</p>
<pre>(nitrogen@localhost)2&gt; sync:go().
Recompile: ./src/pages/web_index
./src/pages/web_index.erl:12: Warning: a term is constructed, but never used
ok</pre>
<p>sync:go() will turn into one of you best friends because it will compile all the files you have changed <img src='http://sergioveiga.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>You can see a warning, that is mainly telling that you have some code, that in never used, and if you go to the browser, and can see that you only have the button there. So what happen to the textbox? Like i told you before, erlang only returns the last code line, so mainly you are only returning the button. To return all you just need to do this:</p>
<pre>body()-&gt;
[
#textbox{text="some text"},
#button{text="hello"}
].</pre>
<p>Mainly you just need to add your elements to a list. In erlang [] is a list, not an array.  Lists are on of the most used structures so bookmark this <a href="http://erlang.org/doc/man/lists.html">link</a>, you will need it for sure.</p>
<p>Now sync again and go to the browser. You should see now a input text element and a button <img src='http://sergioveiga.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>Nitrogen has also a set of built in functions that do a lot of stuff for you. For example the wf:render one.</p>
<pre>body()-&gt;
Elements = [
#textbox{id=input_id, text="some text"},
#button{text="hello"}
],
wf:render(Elements).</pre>
<p>This does exactly the same as before but let you organize the code, the way you like most, what is always great.</p>
<p>So now that you know the alphabet lets start making words <img src='http://sergioveiga.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<h2>Nitrogen Actions</h2>
<p>The interaction between user and application, nitrogen calls it actions. So lets add some actions to our previous button.</p>
<p>pre #button{text=&#8221;hello&#8221;,actions=#event{type=click,postback=hello}} /pre</p>
<p>This will tell the button that on click, will execute the hello event.</p>
<p>So the next thing you need to do is the hello event</p>
<pre>event(hello)-&gt;
io:format("~p~n",["test message"]);

event(_) -&gt; ok.</pre>
<p>sync:go(), and click on hello button and go back to your erlang shell.</p>
<p>You have just created your first client server interaction <img src='http://sergioveiga.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> . If you are using firebug you can easily see that this is done using an AJAX Event, where all the page info is send to the server, and matched to the specific event.</p>
<p>Now lets grab some info</p>
<pre>event(hello)-&gt;
Input = wf:q("input_id"),
io:format("~p~n",[Input]);</pre>
<p>sync:go(), and after clicking again go to erlang shell.</p>
<pre> (nitrogen@localhost)1&gt; ["some text"]</pre>
<p>As you can see using nitrogen wf:q(id) function you have access to input box value. In resume you can access to all parameters sent in a get or post request. Lets test get parameters. Change your body function to this:</p>
<pre>body()-&gt;
Input = wf:q("input_id"),
io:format("~p~n",[Input]),

Elements = [
#textbox{id=input_id, text="some text"},
#button{text="hello",actions=#event{type=click,postback=hello}}
],
wf:render(Elements).</pre>
<p>sync:go(), and change url to <a href="http://localhost:8000/?input_id=hello">http://localhost:8000/?input_id=hello</a></p>
<p>As you can see it work exactly the same, the important thing to remember is that wf:q can only read the header parameters of the request, so for example if now you click on the button, you are creating another request, and input_id=hello from the previous one does not exist.</p>
<p>Now as you can see the output comes inside a list, that we dont really want, so lets remove the element from the list. Replace Input with this:</p>
<pre> hd(wf:q("input_id"))</pre>
<p>sync:go(), and call the url again ( <a href="http://localhost:8000/?input_id=hello ">http://localhost:8000/?input_id=hello </a>). You should be able to see only the string with no list.</p>
<p>But now call the url without any parameter <a href="http://localhost:8000/">http://localhost:8000/</a></p>
<p>Say hello to your first of many erlang errors! Go back to the shell, and you will see exactly what happened</p>
<pre>[{erlang,hd,[[]]},
{web_index,body,0},
{element_template,eval_callbacks,2},
{element_template,eval,2},
{element_template,eval,2},
{element_template,eval,2},
{element_template,eval,2},
{element_template,eval,2}]</pre>
<p>Here you have info of witch module and function create the error {web_index,body,0}, and also witch instruction erlang,hd,[[]], and in resume the problem is that you are trying to get the head of an empty list.</p>
<p>In order to solve this we will introduce on of the most common structures in a erlang code, the case statement. As you probably have heard erlang does not have if statement, its false it has, but in the end you never need to use it, because the case really solves all your problems. So lets change again the Input :</p>
<pre>Input = case wf:q("input_id") of
 <span style="padding-left:50px">[]-&gt;</span>
 <span style="padding-left:75px">"Oops, not input!";</span>
 <span style="padding-left:50px">_-&gt;</span>
 <span style="padding-left:75px">hd(wf:q("input_id"))</span>
 end,</pre>
<p>Case works like it is supposed to be, it will evaluate the return of wf:q and if it evaluates to [], what happens when you dont have the parameter defined, it will associate the string &#8220;Oops, not input!&#8221; to Input, or if it is something else (_) does not matter what, it will grab the head of the list.</p>
<p>Since erlang lives a lot of pattern matching, _ option is a powerful arm for your arsenal <img src='http://sergioveiga.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>Import reminder, and one of the most annoying stuff around erlang, is that the way you end your instruction (, or ; or .) its not a coincidence.<br />
In resume, the end of a function is indicated by the dot (.), but if your function uses pattern matching with the same number of arguments, like it happens on event, only the last one ends with the (.) all the others end with (;).</p>
<pre>event(hello)-&gt;
Input = hd(wf:q("input_id")),
io:format("~p~n",[Input]);

event(_) -&gt; ok.</pre>
<p>All other instruction always end with comma (,) with exception of case instruction where the different options are ended also with (;) and the last one does not need any, like you have seen in the previous example.</p>
<p>Back to the action itself, we were just sending an Atom (erlang simple structure, any word starting with a lower_case <img src='http://sergioveiga.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  ), but we can send info in the postback. Replace postback with this:</p>
<pre> postback={hello,"Hello, i'm string!"}</pre>
<p>and adapt your event to receive the new info</p>
<pre>event({hello,Item})-&gt;
io:format("~p~n",[Item]);</pre>
<p>sync:go,  and as should see how easy its to pass info into events.</p>
<p>Now that you have understood the basics around nitrogen its time to check more complex example, and the cool nitrogen elements, like the comet! So lets continue to <a href="http://sergioveiga.com/index.php/2009/12/03/erlang-on-nitro-erlang-web-development-tutorial-part-23/">part 2 </a>of this tutorial, where we will build a twitter visualization using twitter stream api.</p>
<p style="white-space:nowrap"><img style="border:0px" src="http://tarpipe.com/img/tarpipe.png" />&nbsp;<a target="_blank" href="http://tarpipe.com/share/?t=Erlang+On+Nitro+%E2%80%93+Erlang+Web+Development+Tutorial+%E2%80%93+Part+1%2F3&u=http%3A%2F%2Fsergioveiga.com%2Findex.php%2F2009%2F12%2F02%2Ferlang-on-nitro-erlang-web-development-tutorial-part-13%2F&b=Reading %22Erlang+On+Nitro+%E2%80%93+Erlang+Web+Development+Tutorial+%E2%80%93+Part+1%2F3%22">Share now!</a></p>]]></content:encoded>
			<wfw:commentRss>http://sergioveiga.com/index.php/2009/12/02/erlang-on-nitro-erlang-web-development-tutorial-part-13/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Wikipedia PT Search Engine for FireFox</title>
		<link>http://sergioveiga.com/index.php/2009/10/27/wikipedia-pt-search-engine/</link>
		<comments>http://sergioveiga.com/index.php/2009/10/27/wikipedia-pt-search-engine/#comments</comments>
		<pubDate>Tue, 27 Oct 2009 03:12:50 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[wikipedia]]></category>

		<guid isPermaLink="false">http://sergioveiga.com/?p=47</guid>
		<description><![CDATA[Sometimes i have the feeling that even on the internet when i really need something i never find it&#8230; i find hard to believe that there isn&#8217;t already a firefox search engine for portuguese articles in wikipedia&#8230; damm it, i losted 30 minutes and i have build one ->  Add Portuguese Wikipedia Search Engine [...]]]></description>
			<content:encoded><![CDATA[<p>Sometimes i have the feeling that even on the internet when i really need something i never find it&#8230; i find hard to believe that there isn&#8217;t already a firefox search engine for portuguese articles in wikipedia&#8230; damm it, i losted 30 minutes and i have build one -> <a onclick="window.external.AddSearchProvider('http://sergioveiga.com/wikipedia-pt.xml')" href="Javascript:void(0)"> Add Portuguese Wikipedia Search Engine </a></p>
<p>At least now i have an idea how easy is to create one for my own services <img src='http://sergioveiga.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>To build your own all you need to do is create a file like this one, read more <a href="https://developer.mozilla.org/en/Creating_OpenSearch_plugins_for_Firefox#Autodiscovery_of_search_plugins">here</a> </p>
<script src="http://gist.github.com/219268.js"></script>
<p style="white-space:nowrap"><img style="border:0px" src="http://tarpipe.com/img/tarpipe.png" />&nbsp;<a target="_blank" href="http://tarpipe.com/share/?t=Wikipedia+PT+Search+Engine+for+FireFox&u=http%3A%2F%2Fsergioveiga.com%2Findex.php%2F2009%2F10%2F27%2Fwikipedia-pt-search-engine%2F&b=Reading %22Wikipedia+PT+Search+Engine+for+FireFox%22">Share now!</a></p>]]></content:encoded>
			<wfw:commentRss>http://sergioveiga.com/index.php/2009/10/27/wikipedia-pt-search-engine/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Erlang Poker Server + HTML5 Canvas</title>
		<link>http://sergioveiga.com/index.php/2009/10/27/erlang-poker-server-html5-canvas/</link>
		<comments>http://sergioveiga.com/index.php/2009/10/27/erlang-poker-server-html5-canvas/#comments</comments>
		<pubDate>Tue, 27 Oct 2009 00:52:00 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[blabla]]></category>
		<category><![CDATA[canvas]]></category>
		<category><![CDATA[erlang]]></category>
		<category><![CDATA[ideas]]></category>

		<guid isPermaLink="false">http://sergioveiga.com/?p=39</guid>
		<description><![CDATA[Hey, today i was walking around git-hub checking some erlang projects, and i found this really great erlang poker server, from the greater Joel Reymont.
Well to be honest i dont really give a damm about poker, i never played it, online or in real world, but i have a lot of friends completely addicted to [...]]]></description>
			<content:encoded><![CDATA[<p>Hey, today i was walking around git-hub checking some erlang projects, and i found this really great <a href="http://github.com/wagerlabs/openpoker">erlang poker server</a>, from the greater Joel Reymont.</p>
<p>Well to be honest i dont really give a damm about poker, i never played it, online or in real world, but i have a lot of friends completely addicted to it, so its a topic that catches my attention.</p>
<p>So i start to wonder how great would be to build a client to this server, and i remember a discussion i had earlier with <a rel="nofollow" target="_blank" href="http://twitter.com/telmodias">@telmodias</a>and <a rel="nofollow" target="_blank" href="http://twitter.com/jclopes">@jclopes</a>about htm5 canvas and flash, and the battle to control rich interface applications. EUREKA! Lets build a client for the openpoker server using canvas, to prove that its possible to build a rich interface like the ones exist today in flash (like this <a href="http://www.facebook.com/apps/application.php?id=2389801228&amp;ref=search&amp;sid=516342272.3199622068..1">one</a> ) much more lighter and faster.</p>
<p>Since i have tons of other projects to work in, this is going to the &#8220;when i get time&#8221; department, and then probably to oblivion&#8230; so i would be really happy to help anybody that would like to really do it <img src='http://sergioveiga.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>If you are not convinced check <a href="http://9elements.com/io/?p=153">9elements</a> experiment of canvas, just amazing <img src='http://sergioveiga.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p style="white-space:nowrap"><img style="border:0px" src="http://tarpipe.com/img/tarpipe.png" />&nbsp;<a target="_blank" href="http://tarpipe.com/share/?t=Erlang+Poker+Server+%2B+HTML5+Canvas&u=http%3A%2F%2Fsergioveiga.com%2Findex.php%2F2009%2F10%2F27%2Ferlang-poker-server-html5-canvas%2F&b=Reading %22Erlang+Poker+Server+%2B+HTML5+Canvas%22">Share now!</a></p>]]></content:encoded>
			<wfw:commentRss>http://sergioveiga.com/index.php/2009/10/27/erlang-poker-server-html5-canvas/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Hello World in Erlang</title>
		<link>http://sergioveiga.com/index.php/2009/10/23/hello-world-in-erlang/</link>
		<comments>http://sergioveiga.com/index.php/2009/10/23/hello-world-in-erlang/#comments</comments>
		<pubDate>Fri, 23 Oct 2009 16:46:45 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[erlang]]></category>

		<guid isPermaLink="false">http://sergioveiga.com/?p=14</guid>
		<description><![CDATA[Before you star reading, caution, ERLANG i highly vicious and can cause you to hate any other programming languages you are used to.
Install Erlang
apt-get install erlang
now lets start with the most simple code you can write in erlang
Save it as hello.erl and run erlang shell
erl
Now you can compile hello.erl from the erlang shell. Don&#8217;t forget [...]]]></description>
			<content:encoded><![CDATA[<p>Before you star reading, caution, ERLANG i highly vicious and can cause you to hate any other programming languages you are used to.</p>
<p>Install Erlang</p>
<p><code>apt-get install erlang</code></p>
<p>now lets start with the most simple code you can write in erlang</p>
<script src="http://gist.github.com/216997.js"></script>
<p>Save it as hello.erl and run erlang shell</p>
<p><code>erl</code></p>
<p>Now you can compile hello.erl from the erlang shell. Don&#8217;t forget the full-stop (&#8221;period&#8221; in American English) at the end of each command. After you just need to execute Module:Function().</p>
<p><code><br />
Erlang R13B01 (erts-5.7.2) [source] [rq:1] [async-threads:0] [hipe] [kernel-poll:false]<br />
Eshell V5.7.2  (abort with ^G)<br />
1&gt; c(hello).<br />
{ok,hello}<br />
2&gt;hello:start().<br />
Hello, World!ok<br />
3&gt;<br />
</code></p>
<p>Now that that you are not long afraid of erlang, lets show some of the mighty power everybody talks about, and build &#8220;hello world elang style&#8221; <img src='http://sergioveiga.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
<p>copy the code above</p>
<script src="http://gist.github.com/217014.js"></script>
<p>now compile the code, and execute the following commands</p>
<p><code><br />
Erlang R13B (erts-5.7.1) [source] [smp:2:2] [rq:2] [async-threads:0] [hipe] [kernel-poll:false]</code><br />
Eshell V5.7.1  (abort with ^G)<br />
1&gt; c(hello2).<br />
{ok,hello2}<br />
2&gt; Pid = hello2:start().<br />
&lt;0.39.0&gt;<br />
3&gt; Pid ! hello.<br />
Hello, World!<br />
hello<br />
4&gt; Pid ! goodbye.<br />
goodbye<br />
5&gt; Pid ! hello.<br />
hello<br />
6&gt;</p>
<p>In resume what you have just did, was create a new process with a process id = Pid, that will be waiting for messages. When it receives the message hello, it prints Hello World, and it calls itself to continue listening, when you send the message goodbye the process just finishes execution and dye.</p>
<p>All this with just a few lines of code, and a very simple syntax <img src='http://sergioveiga.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> , but this is just the beginning, now imagine that this process can be running in any machine in the world, and you still can use exactly the same code! This and much more WOW effects is what makes erlang so amazing.</p>
<p>Now in order to really learn erlang i recommend you to get  Joe Armstrong the erlang creator,<br />
<a href="http://pragprog.com/titles/jaerlang/programming-erlang">Programming Erlang: Software for a Concurrent World</a> book and visit the erlang best documentation repo <a href="http://erlang.org/doc/">http://erlang.org/doc/</a></p>
<p>Please check also the <a href="http://egarson.blogspot.com/2008/03/real-erlang-hello-world.html">source and inspiration</a> for this post.</p>
<p style="white-space:nowrap"><img style="border:0px" src="http://tarpipe.com/img/tarpipe.png" />&nbsp;<a target="_blank" href="http://tarpipe.com/share/?t=Hello+World+in+Erlang&u=http%3A%2F%2Fsergioveiga.com%2Findex.php%2F2009%2F10%2F23%2Fhello-world-in-erlang%2F&b=Reading %22Hello+World+in+Erlang%22">Share now!</a></p>]]></content:encoded>
			<wfw:commentRss>http://sergioveiga.com/index.php/2009/10/23/hello-world-in-erlang/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
