<?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/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>Erlware Blog</title>
	<atom:link href="http://blog.erlware.org/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.erlware.org</link>
	<description>Erlang tools and packages</description>
	<lastBuildDate>Tue, 16 Apr 2013 04:47:57 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='blog.erlware.org' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://s2.wp.com/i/buttonw-com.png</url>
		<title>Erlware Blog</title>
		<link>http://blog.erlware.org</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://blog.erlware.org/osd.xml" title="Erlware Blog" />
	<atom:link rel='hub' href='http://blog.erlware.org/?pushpress=hub'/>
		<item>
		<title>Deal of the Day &#8211; Half off Erlang and OTP in Action</title>
		<link>http://blog.erlware.org/2013/04/15/deal-of-the-day-half-off-erlang-and-otp-in-action/</link>
		<comments>http://blog.erlware.org/2013/04/15/deal-of-the-day-half-off-erlang-and-otp-in-action/#comments</comments>
		<pubDate>Tue, 16 Apr 2013 04:47:53 +0000</pubDate>
		<dc:creator>Eric B Merritt</dc:creator>
				<category><![CDATA[Announcements]]></category>

		<guid isPermaLink="false">http://blog.erlware.org/?p=789</guid>
		<description><![CDATA[Here is your chance to get our book Erlang and OTP in Action for half price on April 16th. Use code dotd0416au at www.manning.com/logan/<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.erlware.org&#038;blog=19876286&#038;post=789&#038;subd=erlware&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>Here is your chance to get our book Erlang and OTP in Action for half price on April 16th. Use code dotd0416au at <a href="http://www.manning.com/logan/">www.manning.com/logan/</a></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/erlware.wordpress.com/789/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/erlware.wordpress.com/789/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.erlware.org&#038;blog=19876286&#038;post=789&#038;subd=erlware&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://blog.erlware.org/2013/04/15/deal-of-the-day-half-off-erlang-and-otp-in-action/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/1c32ef01b258b3b5ca43d8da88653fb4?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">cyberlync</media:title>
		</media:content>
	</item>
		<item>
		<title>Running Opa Applications on Heroku</title>
		<link>http://blog.erlware.org/2012/11/12/running-opa-applications-on-heroku/</link>
		<comments>http://blog.erlware.org/2012/11/12/running-opa-applications-on-heroku/#comments</comments>
		<pubDate>Mon, 12 Nov 2012 15:07:50 +0000</pubDate>
		<dc:creator>Tristan Sloughter</dc:creator>
				<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[Web Development]]></category>
		<category><![CDATA[buildpacks]]></category>
		<category><![CDATA[heroku]]></category>
		<category><![CDATA[node.js]]></category>
		<category><![CDATA[Opa]]></category>
		<category><![CDATA[web development]]></category>

		<guid isPermaLink="false">http://blog.erlware.org/?p=776</guid>
		<description><![CDATA[TL;DR Opa Buildpack Example Opa application source Example Opa application running on Heroku As I&#8217;ve mentioned before, Opa is a new web framework that introduces not only the framework itself but a whole new language. A lot has changed in Opa since I last posted about it. Now Opa has a Javascript-esque look and runs [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.erlware.org&#038;blog=19876286&#038;post=776&#038;subd=erlware&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p><strong>TL;DR</strong></p>
<ul>
<ul>
<li><a title="Heroku Buildpack Opa" href="https://github.com/tsloughter/heroku-buildpack-opa">Opa Buildpack</a></li>
<li><a title="Opa hello_chat for Heroku" href="https://github.com/tsloughter/hello_chat">Example Opa application source</a></li>
<li><a href="http://mighty-garden-9304.herokuapp.com">Example Opa application running on Heroku</a></li>
</ul>
</ul>
<p>As I&#8217;ve mentioned before, <a title="Opa" href="http://opalang.org">Opa</a> is a new web framework that introduces not only the framework itself but a whole new language. A lot has changed in Opa since I last posted about it. Now Opa has a Javascript-esque look and runs on Node.js. But it still has the amazing typing system that makes Opa a joy to code in.</p>
<p>The currently available <a title="Heroku" href="http://heroku.com">Heroku</a> buildpack for Opa only supported the old, pre-Node, support. So I&#8217;ve created an all new buildpack and here I will show both a bit of how I created that buildpack and how to use it to run your Opa apps on Heroku.</p>
<p>The first step was creating a tarball of Opa that would work on Heroku. For this I used the build tool <a title="Vulcan" href="https://github.com/heroku/vulcan">vulcan</a>. Vulcan is able to build software on Heroku in order to assure what is built will work on Heroku through your buildpacks.</p>
<pre style="color:#dcdccc;background-color:#3f3f3f;">vulcan build -v -s ./opalang/ -c "mkdir /app/mlstate-opa &amp;&amp; yes '' | ./opa-1.0.7.x64.run" -p /app/mlstate-opa</pre>
<p>This command is telling vulcan to build what is in the directory <em>opalang</em> with a command that creates the directory <em>/app/mlstate-opa</em> and then runs the Opa provided install script to unpack the system. This is much simpler than building Opa from source, but it is still necessary to still use vulcan to create the tarball from the output of the install script to ensure paths are correct in the Opa generated scripts.</p>
<p>After this run, by vulcan&#8217;s default, we will have <em>/tmp/opalang.tgz</em>. I upload this to S3, so that our buildpack is able to retrieve it.</p>
<p>Since Opa now relies on Node.js, the new buildpack must install both Node.js and the <em>opalang.tgz</em> that was generated. To do this I simply copied from the <a title="Heroku Buildpack Node.js" href="https://github.com/heroku/heroku-buildpack-nodejs">Node.js buildpack</a>.</p>
<p>If you look at the <a title="Heroku Buildpack Opa" href="https://github.com/tsloughter/heroku-buildpack-opa">Opa buildpack</a> you&#8217;ll see, as with any buildpack, it consists of three main scripts under <em>./bin/</em>: <em>compile</em>, <em>detect</em> and <em>release</em>. There are three important parts for understanding how your Opa app must be changed to be supported by the buildpack.</p>
<p>First, the <em>detect</em> script relies on there being a <em>opa.conf</em> to detect this being an Opa application. This for now is less important since we will be specifying the buildpack to use to the <em>heroku</em> script. Second, in the <em>compile</em> script we rely on there being a <em>Makefile</em> in your application for building. There is no support for simply running <em>opa</em> to compile the code in your tree at this time. Third, since Opa relies on Node.js and Node modules from <em>npm</em> you must provide a <em>package.json</em> file that the <em>compile</em> script uses to install the necessary modules.</p>
<p>To demostrate this I converted Opa&#8217;s <a title="Opa hello_chat" href="https://github.com/MLstate/hello_chat">hello_chat</a> example to work on Heroku, see it on Github <a title="Heroku Opa hello_chat" href="https://github.com/tsloughter/hello_chat">here</a>.</p>
<p>There are two necessary changes. One, add the <em>Procfile</em>. A <em>Procfile</em> define the processes required for your application and how to run them. For <em>hello_chat</em> we have:</p>
<pre style="color:#dcdccc;background-color:#3f3f3f;">web: ./hello_chat.exe --http-port $PORT</pre>
<p>This tell Heroku that our web process is run from the binary <em>hello_chat.exe</em>. We must pass the <em>$PORT </em>variable to the Opa binary so that it binds to the proper port that Heroku expects it to be listening on to route our traffic.</p>
<p>Lastly, a <em>package.json</em> file is added so that our buildpack&#8217;s compile script installs the necessary Node.js modules:</p>
<pre style="color:#dcdccc;background-color:#3f3f3f;">{
  <span style="color:#cc9393;">"name"</span>: <span style="color:#cc9393;">"hello_chat"</span>,
  <span style="color:#cc9393;">"version"</span>: <span style="color:#cc9393;">"0.0.1"</span>,
  <span style="color:#cc9393;">"dependencies"</span>: {
      <span style="color:#cc9393;">"mongodb"</span> : <span style="color:#cc9393;">"*"</span>,
      <span style="color:#cc9393;">"formidable"</span> : <span style="color:#cc9393;">"*"</span>,
      <span style="color:#cc9393;">"nodemailer"</span> : <span style="color:#cc9393;">"*"</span>,
      <span style="color:#cc9393;">"simplesmtp"</span> : <span style="color:#cc9393;">"*"</span>,
      <span style="color:#cc9393;">"imap"</span> : <span style="color:#cc9393;">"*"</span>
  },
  <span style="color:#cc9393;">"engines"</span>: {
    <span style="color:#cc9393;">"node"</span>: <span style="color:#cc9393;">"0.8.7"</span>,
    <span style="color:#cc9393;">"npm"</span>: <span style="color:#cc9393;">"1.1.x"</span>
  }
}</pre>
<p>With these additions to <em>hello_chat</em> we are ready to create an Opa app on Heroku and push the code!</p>
<pre style="color:#dcdccc;background-color:#3f3f3f;">$ heroku create <span style="color:#7f9f7f;">--stack</span> cedar <span style="color:#7f9f7f;">--buildpack</span> https://github.com/tsloughter/heroku-buildpack-opa.git
$ git push heroku master</pre>
<p>The output from the push will show Node.js and npm being install, followed by Opa being unpacked and finally make being run against hello_chat. The web process in <em>Procfile</em> will then be run and the output will provide a link to go to our new application. I have the example running at <a href="http://mighty-garden-9304.herokuapp.com">http://mighty-garden-9304.herokuapp.com</a></p>
<p>Next time I&#8217;ll delve into database and other addon support in Heroku with Opa applications.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/erlware.wordpress.com/776/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/erlware.wordpress.com/776/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.erlware.org&#038;blog=19876286&#038;post=776&#038;subd=erlware&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://blog.erlware.org/2012/11/12/running-opa-applications-on-heroku/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://2.gravatar.com/avatar/e9f10146ae0cd7082107b227598f56c2?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">kungfooguru</media:title>
		</media:content>
	</item>
		<item>
		<title>Projmake-mode: Flymake Replacement</title>
		<link>http://blog.erlware.org/2012/09/27/projmake-mode-flymake-replacement/</link>
		<comments>http://blog.erlware.org/2012/09/27/projmake-mode-flymake-replacement/#comments</comments>
		<pubDate>Thu, 27 Sep 2012 18:13:47 +0000</pubDate>
		<dc:creator>Tristan Sloughter</dc:creator>
				<category><![CDATA[Erlang]]></category>
		<category><![CDATA[Erlware]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[Emacs]]></category>
		<category><![CDATA[Functional Programming]]></category>
		<category><![CDATA[OTP]]></category>
		<category><![CDATA[rebar]]></category>

		<guid isPermaLink="false">http://blog.erlware.org/?p=724</guid>
		<description><![CDATA[There is a great new Emacs plugin from Eric Merritt that like FlyMake builds your code and highlights within Emacs any errors or warnings, but unlike FlyMake builds across the whole project. You can clone the mode from here projmake-mode After cloning the repo to your desired location add this bit to your dot emacs [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.erlware.org&#038;blog=19876286&#038;post=724&#038;subd=erlware&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>There is a great new <a title="Emacs" href="http://www.gnu.org/software/emacs/">Emacs</a> plugin from <a title="Eric Merritt" href="http://blog.ericbmerritt.com/">Eric Merritt</a> that like <a title="FlyMake" href="http://www.emacswiki.org/emacs/FlyMake">FlyMake</a> builds your code and highlights within Emacs any errors or warnings, but unlike FlyMake builds across the whole project. You can clone the mode from here <a title="projmake-mode" href="https://github.com/ericbmerritt/projmake-mode">projmake-mode</a></p>
<p>After cloning the repo to your desired location add this bit to your dot emacs file, replacing <em>&lt;PATH&gt;</em> with the path to where you cloned the repo.</p>
<script src="https://gist.github.com/3794732.js"></script>
<p>This Emacs code also uses <em>add-hook</em> to set <em>projmake-mode</em> to start for <em>erlang-mode</em> is loaded. Projmake by default knows how to handle <a title="rebar" href="https://github.com/basho/rebar">rebar</a> and Make based builds so there is no setup after this, assuming your project is built this way.</p>
<p>Here is my <em>Makefile</em> for building Erlang projects with rebar, replace <em>PROJECT<em> with the name of your project:</em></em></p>
<script src="https://gist.github.com/3795007.js"></script>
<p>Now you can load Emacs and a file from your project and if it is an Erlang file due to the <em>add-hook</em> function in our dot emacs file it will automatically load projmake-mode. You can add hooks for other modes or simply run <em>M-x projmake-mode</em>.</p>
<p>For more documentation and how to extend to other types of projects check out the <a title="README" href="https://github.com/ericbmerritt/projmake-mode/blob/master/README.md">documentation</a>.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/erlware.wordpress.com/724/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/erlware.wordpress.com/724/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.erlware.org&#038;blog=19876286&#038;post=724&#038;subd=erlware&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://blog.erlware.org/2012/09/27/projmake-mode-flymake-replacement/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://2.gravatar.com/avatar/e9f10146ae0cd7082107b227598f56c2?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">kungfooguru</media:title>
		</media:content>
	</item>
		<item>
		<title>Maru Models: JSON to Erlang Record with Custom Types</title>
		<link>http://blog.erlware.org/2012/09/26/maru-models-json-to-erlang-record-with-custom-types/</link>
		<comments>http://blog.erlware.org/2012/09/26/maru-models-json-to-erlang-record-with-custom-types/#comments</comments>
		<pubDate>Wed, 26 Sep 2012 18:43:44 +0000</pubDate>
		<dc:creator>Tristan Sloughter</dc:creator>
				<category><![CDATA[Erlang]]></category>

		<guid isPermaLink="false">http://blog.erlware.org/?p=485</guid>
		<description><![CDATA[Working with Erlang for writing RESTful interfaces JSON is the communication &#8220;language&#8221; of choice. For simplifying the process of JSON to a model the backend could work with efficiently I&#8217;ve created maru_models. This app decodes the JSON with jiffy and uses functions generated by a modified version of Ulf&#8217;s exprecs to create an Erlang record. [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.erlware.org&#038;blog=19876286&#038;post=485&#038;subd=erlware&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>Working with Erlang for writing RESTful interfaces JSON is the communication &#8220;language&#8221; of choice. For simplifying the process of JSON to a model the backend could work with efficiently I&#8217;ve created <em>maru_models</em>. This app decodes the JSON with <em>jiffy</em> and uses functions generated by a modified version of Ulf&#8217;s <em>exprecs</em> to create an Erlang record. The generated functions are created with type information from the record definition and when a property is set for the record through these functions it is first passed to the <em>convert</em> function of <em>maru_model_types</em> to do any necessary processing. </p>
<p>I separated this application into a separate repo to simplify people trying the examples. But the real development will be done in the Maru main repo.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/erlware.wordpress.com/485/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/erlware.wordpress.com/485/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.erlware.org&#038;blog=19876286&#038;post=485&#038;subd=erlware&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://blog.erlware.org/2012/09/26/maru-models-json-to-erlang-record-with-custom-types/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
	
		<media:content url="http://2.gravatar.com/avatar/e9f10146ae0cd7082107b227598f56c2?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">kungfooguru</media:title>
		</media:content>
	</item>
		<item>
		<title>Getting Flymake and Rebar to Play Nice</title>
		<link>http://blog.erlware.org/2012/05/15/getting-flymake-and-rebar-to-play-nice/</link>
		<comments>http://blog.erlware.org/2012/05/15/getting-flymake-and-rebar-to-play-nice/#comments</comments>
		<pubDate>Tue, 15 May 2012 20:39:32 +0000</pubDate>
		<dc:creator>Eric B Merritt</dc:creator>
				<category><![CDATA[Erlang]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[Emacs]]></category>

		<guid isPermaLink="false">http://blog.erlware.org/?p=716</guid>
		<description><![CDATA[TLDR; Copy and paste the following into your elisp erlang-mode configuration to get flymake working with Rebar projects. (defun ebm-find-rebar-top-recr (dirname) (let* ((project-dir (locate-dominating-file dirname "rebar.config"))) (if project-dir (let* ((parent-dir (file-name-directory (directory-file-name project-dir))) (top-project-dir (if (and parent-dir (not (string= parent-dir "/"))) (ebm-find-rebar-top-recr parent-dir) nil))) (if top-project-dir top-project-dir project-dir)) project-dir))) (defun ebm-find-rebar-top () (interactive) (let* ((dirname [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.erlware.org&#038;blog=19876286&#038;post=716&#038;subd=erlware&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p><strong>TLDR;</strong><br />
Copy and paste the following into your elisp erlang-mode configuration to get flymake working with Rebar projects.</p>
<pre>
 (defun ebm-find-rebar-top-recr (dirname)
      (let* ((project-dir (locate-dominating-file dirname "rebar.config")))
        (if project-dir
            (let* ((parent-dir (file-name-directory (directory-file-name project-dir)))
                   (top-project-dir (if (and parent-dir (not (string= parent-dir "/")))
                                       (ebm-find-rebar-top-recr parent-dir)
                                      nil)))
              (if top-project-dir
                  top-project-dir
                project-dir))
              project-dir)))

    (defun ebm-find-rebar-top ()
      (interactive)
      (let* ((dirname (file-name-directory (buffer-file-name)))
             (project-dir (ebm-find-rebar-top-recr dirname)))
        (if project-dir
            project-dir
          (erlang-flymake-get-app-dir))))

     (defun ebm-directory-dirs (dir name)
        "Find all directories in DIR."
        (unless (file-directory-p dir)
          (error "Not a directory `%s'" dir))
        (let ((dir (directory-file-name dir))
              (dirs '())
              (files (directory-files dir nil nil t)))
            (dolist (file files)
              (unless (member file '("." ".."))
                (let ((absolute-path (expand-file-name (concat dir "/" file))))
                  (when (file-directory-p absolute-path)
                    (if (string= file name)
                        (setq dirs (append (cons absolute-path
                                                 (ebm-directory-dirs absolute-path name))
                                           dirs))
                        (setq dirs (append
                                    (ebm-directory-dirs absolute-path name)
                                    dirs)))))))
              dirs))

    (defun ebm-get-deps-code-path-dirs ()
        (ebm-directory-dirs (ebm-find-rebar-top) "ebin"))

    (defun ebm-get-deps-include-dirs ()
       (ebm-directory-dirs (ebm-find-rebar-top) "include"))

    (fset 'erlang-flymake-get-code-path-dirs 'ebm-get-deps-code-path-dirs)
    (fset 'erlang-flymake-get-include-dirs-function 'ebm-get-deps-include-dirs)
</pre>
<p><strong>Intro</strong></p>
<p>Its probably no great surprise to anyone that I dislike <a href="https://github.com/basho/rebar" title="Rebar">Rebar</a> a lot. That said there are times when I have no choice but to use it. This is always either because a company I am contracting for uses it, or an open source project I am contributing to uses it. When I am forced to use it there are a few things I don&#8217;t want to give up. Most important among these is <a href="http://flymake.sourceforge.net/" title="Flymake">Flymake</a> for Erlang. The default setup for Flymake doesn&#8217;t work for Rebar projects because Flymake does not know where the code and include paths for dependencies are. Fortunately, we can fix this with a few lines of elisp.</p>
<p><strong>Flymake For Erlang</strong></p>
<p>First make sure you have Flymake for Erlang installed. It is easiest just <a href="http://www.erlang.org/doc/apps/tools/erlang_mode_chapter.html" title="Erlang Flymake Instructions">to follow the directions available on the Erlang Website</a>.</p>
<p><strong>The Elisp Additions for Erlang Flymake</strong></p>
<p>There are two defvars that point to functions that are used to search for the correct code paths and include paths respectively. We are going to replace those functions with our own functions. Both these functions search upwards from the directory that contains the file pointed to by the current buffer, looking for the top most &#8216;rebar.config&#8217; in the directory path. It then uses that for a base and searches down the directory structure looking for either &#8216;ebin&#8217; files or &#8216;include&#8217; files.</p>
<p>There are two things to note here. The first is that you must have already run `get-deps` for rebar for this to work and the second is that if your project is truly huge or you have way more dependencies then you probably need this search could take a second or two. That is a second or two too long in an interactive compiler like Flymake. That said, the likelihood that you will run into this second problem is quite low.</p>
<p><strong>Getting Started</strong></p>
<p>The very thing you want to do is ensure that you have <code>required</code> the <code>erlang-flymake</code> module. Most of what we do below depends on this.</p>
<pre>
(require 'erlang-flymake)
</pre>
<p><strong>Finding the Top rebar.config</strong></p>
<p>The second thing we want to do is look for the top <code>rebar.config</code> in the project. If a rebar project contains more then one OTP application its quite likely that it will contain more then one <code>rebar.config</code>. The very topmost `rebar`config` is the right one to serve as root of our search. So we introduce a set of recursive functions to look for that top level dir.</p>
<pre>
    (defun ebm-find-rebar-top-recr (dirname)
      (let* ((project-dir (locate-dominating-file dirname "rebar.config")))
        (if project-dir
            (let* ((parent-dir (file-name-directory (directory-file-name project-dir)))
                   (top-project-dir (if (and parent-dir (not (string= parent-dir "/")))
                                       (ebm-find-rebar-top-recr parent-dir)
                                      nil)))
              (if top-project-dir
                  top-project-dir
                project-dir))
              project-dir)))
</pre>
<p><code>ebm-find-rebar-top-recr</code> will return either the top most directory or <code>nil</code>. Our next function takes that result and does something useful with.</p>
<pre>
    (defun ebm-find-rebar-top ()
      (interactive)
      (let* ((dirname (file-name-directory (buffer-file-name)))
             (project-dir (ebm-find-rebar-top-recr dirname)))
        (if project-dir
            project-dir
          (erlang-flymake-get-app-dir))))
</pre>
<p>In this function, we get the directory containing the file pointed at by the current buffer. We then call our recr function. If it returns a directory we return that, if it returns nil however, we call the original <code>erlang-flymake-get-app-dir</code> function.</p>
<p>At this point we should have our project root. Now its a simple matter of recursively searching down the directory tree looking for files of a certain name. So we create a function that does just that, given a directory and a name will return a list of absolute paths for each subdirectory that matches the specified name.</p>
<pre>
(defun ebm-directory-dirs (dir name)
        "Find all directories in DIR."
        (unless (file-directory-p dir)
          (error "Not a directory `%s'" dir))
        (let ((dir (directory-file-name dir))
              (dirs '())
              (files (directory-files dir nil nil t)))
            (dolist (file files)
              (unless (member file '("." ".."))
                (let ((absolute-path (expand-file-name (concat dir "/" file))))
                  (when (file-directory-p absolute-path)
                    (if (string= file name)
                        (setq dirs (append (cons absolute-path
                                                 (ebm-directory-dirs absolute-path name))
                                           dirs))
                        (setq dirs (append
                                    (ebm-directory-dirs absolute-path name)
                                    dirs)))))))
              dirs))
</pre>
<p>Now we write a couple of functions to replace the corresponding functions in `erlang-flymake`. The first looks for all `ebin` directories while the second looks for all `include` directories.</p>
<pre>
    (defun ebm-get-deps-code-path-dirs ()
        (ebm-directory-dirs (ebm-find-rebar-top) "ebin"))

    (defun ebm-get-deps-include-dirs ()
       (ebm-directory-dirs (ebm-find-rebar-top) "include"))
</pre>
<p>Finally we replace the `erlang-flymake` versions of those functions with our implementations.</p>
<pre>
(fset 'erlang-flymake-get-code-path-dirs 'ebm-get-deps-code-path-dirs)
(fset 'erlang-flymake-get-include-dirs-function 'ebm-get-deps-include-dirs)
</pre>
<p><strong>Conclusion</strong></p>
<p>This approach is a bit of a hack, we basically use some heuristics to find a root and then just grab everything under that that looks remotely like a code or include directory. While its a bit hacky it has the valuable upside that its flexible and robust.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/erlware.wordpress.com/716/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/erlware.wordpress.com/716/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.erlware.org&#038;blog=19876286&#038;post=716&#038;subd=erlware&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://blog.erlware.org/2012/05/15/getting-flymake-and-rebar-to-play-nice/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/1c32ef01b258b3b5ca43d8da88653fb4?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">cyberlync</media:title>
		</media:content>
	</item>
		<item>
		<title>Erlang Common Test Continuous Integration</title>
		<link>http://blog.erlware.org/2012/05/09/erlang-common-test-continuous-integration/</link>
		<comments>http://blog.erlware.org/2012/05/09/erlang-common-test-continuous-integration/#comments</comments>
		<pubDate>Wed, 09 May 2012 15:01:52 +0000</pubDate>
		<dc:creator>Eric B Merritt</dc:creator>
				<category><![CDATA[Erlang]]></category>
		<category><![CDATA[General Information]]></category>

		<guid isPermaLink="false">http://blog.erlware.org/?p=707</guid>
		<description><![CDATA[Common Test is a well thought out integration testing framework for Erlang. If you are not using it you probably should be. However, it has one fault. It does not return non-negative exit status&#8217; to the caller when the tests fail. This is a major oversight, and it makes it difficult to use as part [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.erlware.org&#038;blog=19876286&#038;post=707&#038;subd=erlware&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p><a href="http://www.erlang.org/doc/apps/common_test/index.html">Common Test</a> is a well thought out integration testing framework for Erlang. If you<br />
are not using it you probably should be. However, it has one fault. It<br />
does not return non-negative exit status&#8217; to the caller when the tests<br />
fail. This is a major oversight, and it makes it difficult to use as<br />
part of a continuous integration scheme or in a make based build<br />
system.
</p>
<p>
The long term fix is for the OTP folks to resolve the issue in the<br />
<code>ct_run</code> command. To that end I have filed a bug report with the<br />
Erlang folks. In the short term, though, we need this behaving<br />
correctly. After much twiddling around with different solutions and<br />
conversions on the erlang-questions list. This solution finally popped<br />
out of a conversation with Lukas Larsson. Basically, we use the old<br />
unix standby of awk.
</p>
<pre>

    ct_run -dir tests  ... | awk "/FAILED/{exit 1;}/failed/{exit 1;}/SKIPPED/{exit 1;}"

</pre>
<p>Where <code>...</code> is replaced with your additional options. Its not the best<br />
solution on the planet, but it is the simplest one that I found that<br />
works consistently.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/erlware.wordpress.com/707/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/erlware.wordpress.com/707/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.erlware.org&#038;blog=19876286&#038;post=707&#038;subd=erlware&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://blog.erlware.org/2012/05/09/erlang-common-test-continuous-integration/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/1c32ef01b258b3b5ca43d8da88653fb4?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">cyberlync</media:title>
		</media:content>
	</item>
		<item>
		<title>Sinan Releases and Being Right</title>
		<link>http://blog.erlware.org/2012/05/04/sinan-releases-and-being-right/</link>
		<comments>http://blog.erlware.org/2012/05/04/sinan-releases-and-being-right/#comments</comments>
		<pubDate>Fri, 04 May 2012 20:33:07 +0000</pubDate>
		<dc:creator>Tristan Sloughter</dc:creator>
				<category><![CDATA[Erlang]]></category>
		<category><![CDATA[Erlware]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[Cowboy]]></category>
		<category><![CDATA[OTP]]></category>
		<category><![CDATA[rebar]]></category>
		<category><![CDATA[sinan]]></category>

		<guid isPermaLink="false">http://blog.erlware.org/?p=691</guid>
		<description><![CDATA[Fred, of Learn You Some Erlang for Great Good, today posted on his blog about the problems around how rebar handles releases, Rebar Releases and Being Wrong. The problems he mentions and a few others are why, despite giving it a legitimate shot, I have found rebar unusable for my workflow to be efficient and [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.erlware.org&#038;blog=19876286&#038;post=691&#038;subd=erlware&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p><a href="http://ferd.ca/">Fred</a>, of <a title="Learn You Some Erlang" href="http://learnyousomeerlang.com/">Learn You Some Erlang for Great Good</a>, today posted on his blog about the problems around how rebar handles releases, <a title="Rebar Releases and Being Wrong" href="http://ferd.ca/rebar-releases-and-being-wrong.html">Rebar Releases and Being Wrong</a>. The problems he mentions and a few others are why, despite giving it a legitimate shot, I have found rebar unusable for my workflow to be efficient and stable while adhering to OTP standards at the same time.</p>
<p>I suggest first reading his post, if you already use rebar, and then continuing on with the rest of this.</p>
<p>I&#8217;ll start with an example on the generation of a project containing two applications and a dependency from one of those applications of <a title="Cowboy" href="https://github.com/extend/cowboy">cowboy</a>. Next, I&#8217;ll create a release (and in the process a deployable target system) to show the difference in how <a title="Sinan" href="https://github.com/erlware/sinan">sinan</a> handles this process.</p>
<p>TL;DR <a title="Sinan" href="https://github.com/erlware/sinan">Sinan</a> does OTP the right way, rebar does not.</p>
<p>First, you can download the latest version sinan from this <a title="Sinan Download" href="https://github.com/downloads/erlware/sinan/sinan">link</a>, it is simply an executable escript, so &#8216;<em>chmod +x sinan</em>&#8216; and put it in your <strong>PATH</strong> and you are good to go.</p>
<p>Sinan provides a &#8216;gen&#8217; command to create your project. I include the output of the steps I took to build this project. Sinan assumes this is a multiple application project, but if you give &#8220;y&#8221; instead it will create a directory structure similar to rebars default structure with a src/ directory instead of a lib/ directory.</p>
<pre style="color:#dcdccc;background-color:#3f3f3f;">$ sinan gen
Please specify your name 
your name&gt; Tristan Sloughter
Please specify your email address 
your email&gt; tristan@mashape.com
Please specify the copyright holder 
copyright holder ("Tristan Sloughter")&gt; 
Please specify name of your project
project name&gt; rel_example
Please specify version of your project
project version&gt; 0.0.1
Please specify the ERTS version ("5.9")&gt; 
Is this a single application project ("n")&gt; 
Please specify the names of the OTP apps that will be developed under this project. One application to a line. Finish with a blank line.
app&gt; app_1
app ("")&gt; app_2
app ("")&gt; 
Would you like a build config? ("y")&gt; y
Project was created, you should be good to go!</pre>
<p>We now have a project named rel_example and can see the generated contents.</p>
<pre style="color:#dcdccc;background-color:#3f3f3f;">$ cd rel_example/
$ ls
config  doc  lib  sinan.config</pre>
<p>Before going further I add the line {include_erts, true}. to sinan.config so that a generated tarball of the release contains erts and can be booted on a machine without Erlang installed.</p>
<pre style="color:#dcdccc;background-color:#3f3f3f;"><span style="color:#bfebbf;">$ </span>cat sinan.config
{project_name, rel_example}.
{project_vsn, <span style="color:#cc9393;">"0.0.1"</span>}.

{build_dir,  <span style="color:#cc9393;">"_build"</span>}.

{ignore_dirs, [<span style="color:#cc9393;">"_"</span>, <span style="color:#cc9393;">"."</span>]}.

{ignore_apps, []}.

{include_erts, true}.</pre>
<p>A tree structure view of the generated project is below:</p>
<pre style="color:#dcdccc;background-color:#3f3f3f;">.
├── config
│   └── sys.config
├── doc
├── lib
│   ├── app_1
│   │   ├── doc
│   │   ├── ebin
│   │   │   └── overview.edoc
│   │   ├── include
│   │   └── src
│   │       ├── app_1_app.erl
│   │       ├── app_1.app.src
│   │       └── app_1_sup.erl
│   └── app_2
│       ├── doc
│       ├── ebin
│       │   └── overview.edoc
│       ├── include
│       └── src
│           ├── app_2_app.erl
│           ├── app_2.app.src
│           └── app_2_sup.erl
└── sinan.config</pre>
<p>You&#8217;ll see we have a lib directory with two applications containing their source files under a src directory. Now in order to boot the release we&#8217;ll create, we need to remove a couple tings from each supervisor. Instead of creating something for them to supervise just remove the variable AChild and replace [AChild] with [].</p>
<p>Next, so we have a third party dependency in the example, add cowboy to the applications in nano lib/app_1/src/app_1.app.src:</p>
<pre style="color:#dcdccc;background-color:#3f3f3f;">{applications, [kernel, stdlib, cowboy]},</pre>
<p>Sinan provides a depends command to show the depenedencies of the project and where they are located:</p>
<pre style="color:#dcdccc;background-color:#3f3f3f;">$ sinan depends <span style="color:#7f9f7f;">-v</span>
<span style="color:#cc9393;">starting: depends</span>
Using the following lib directories to show resolved dependencies and where it found them:

    /home/tristan/.kerl/installs/r15b/lib
    /home/tristan/Devel/rel_example/_build/rel_example/lib

compile time dependencies:

runtime dependencies:

    kernel                    2.15       : /home/tristan/.kerl/installs/r15b/lib/kernel-2.15
    stdlib                    1.18       : /home/tristan/.kerl/installs/r15b/lib/stdlib-1.18
    cowboy                    0.5.0      : /home/tristan/.kerl/installs/r15b/lib/cowboy-0.5.0

project applications:

    app_1                     0.1.0      : /home/tristan/Devel/rel_example/_build/rel_example/lib/app_1-0.1.0
    app_2                     0.1.0      : /home/tristan/Devel/rel_example/_build/rel_example/lib/app_2-0.1.0</pre>
<p>Now lets build a release and target system.</p>
<pre style="color:#dcdccc;background-color:#3f3f3f;">$ sinan dist</pre>
<p>After running the dist command we have a _build directory that we find the following structure. I removed the files/dirs under each app to shorten the listing.</p>
<pre style="color:#dcdccc;background-color:#3f3f3f;">_build/
├── rel_example
│   ├── bin
│   │   ├── rel_example
│   │   └── rel_example-0.0.1
│   ├── erts-5.9
│   │   ├── 
│   ├── lib
│   │   ├── app_1-0.1.0
│   │   │   ├── 
│   │   ├── app_2-0.1.0
│   │   │   ├── 
│   │   ├── cowboy-0.5.0
│   │   │   ├── 
│   │   ├── kernel-2.15
│   │   │   ├── 
│   │   └── stdlib-1.18
│   │       ├── 
│   └── releases
│       └── 0.0.1
│           ├── rel_example.boot
│           ├── rel_example.rel
│           ├── rel_example.script
│           └── sys.config
└── tar
    └── rel_example-0.0.1.tar.<span style="color:#e0cf9f;font-weight:bold;text-decoration:underline;">gz</span></pre>
<p>Sinan has created a lib directory containing all necessary applications for our release as well as the needed files for booting the release. Additionally the dist command creates a tar.gz for easy deployment. But if we simply want to run our release where we are we can:</p>
<pre style="color:#dcdccc;background-color:#3f3f3f;">$ _build/rel_example/bin/rel_example
Erlang R15B (erts-5.9)

<span style="color:#8cd0d3;">[64-bit]</span> <span style="color:#f0dfaf;font-weight:bold;">[smp:4:4]</span> <span style="color:#8cd0d3;">[async-threads:0]</span> <span style="color:#f0dfaf;font-weight:bold;">[hipe]</span> <span style="color:#8cd0d3;">[kernel-poll:false]</span>

<span style="color:#bc8383;font-weight:bold;text-decoration:underline;">Eshell</span> V5.9  (abort with ^G)
1&gt;</pre>
<p>This is only the tip of the iceberg of what sinan is capable of. I can&#8217;t go into all of it here but I&#8217;ll mention that you are able to define multiple releases for a project to generate and which of your project apps to include in each. Additionally you are able to provide a custom rel file if you require tweaks.</p>
<p>The important part to take away from this post is the structure of what you are working with when using sinan and how it is based on OTP standards, both for the source you work on and the results of the build process under _build/.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/erlware.wordpress.com/691/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/erlware.wordpress.com/691/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.erlware.org&#038;blog=19876286&#038;post=691&#038;subd=erlware&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://blog.erlware.org/2012/05/04/sinan-releases-and-being-right/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
	
		<media:content url="http://2.gravatar.com/avatar/e9f10146ae0cd7082107b227598f56c2?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">kungfooguru</media:title>
		</media:content>
	</item>
		<item>
		<title>Cowboy and Batman.js for Erlang Web Development</title>
		<link>http://blog.erlware.org/2012/04/30/cowboy-and-batman-js-for-erlang-web-development/</link>
		<comments>http://blog.erlware.org/2012/04/30/cowboy-and-batman-js-for-erlang-web-development/#comments</comments>
		<pubDate>Mon, 30 Apr 2012 14:59:11 +0000</pubDate>
		<dc:creator>Tristan Sloughter</dc:creator>
				<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[batman.js]]></category>
		<category><![CDATA[Cowboy]]></category>
		<category><![CDATA[Erlang]]></category>
		<category><![CDATA[Javascript]]></category>
		<category><![CDATA[RESTful]]></category>
		<category><![CDATA[web development]]></category>
		<category><![CDATA[Webmachine]]></category>

		<guid isPermaLink="false">http://blog.erlware.org/?p=676</guid>
		<description><![CDATA[Why Cowboy and Batman.js There are a lot of Erlang web frameworks out there today. Not all are modeled after the MVC model (see Nitrogen), but I think all of them are addressing the problem the wrong way. I recently gave a presentation, slides here and the code for this example here, describing my perferred method [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.erlware.org&#038;blog=19876286&#038;post=676&#038;subd=erlware&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<h2>Why Cowboy and Batman.js</h2>
<p>There are a lot of Erlang web frameworks out there today. Not all are modeled after the MVC model (see <a title="Nitrogen" href="http://nitrogenproject.com/">Nitrogen</a>), but I think all of them are addressing the problem the wrong way. I recently gave a presentation, <a title="Chicago Erlang User Group April 4th, 2012" href="http://tsloughter.github.com/ceug_4_2012/">slides here</a> and the <a title="Batman Cowboy MVC" href="https://github.com/tsloughter/bcmvc/">code for this example here</a>, describing my perferred method for using Erlang for web development and why I think it is the best way to go. In this post, I&#8217;ll go into more details on how to build the Erlang backend for the TodoMVC clone I did with <a title="Batman.js" href="http://batmanjs.org/">Batman.js</a>. I will not spend time on Batman.js but instead only give a quick list of reasons I prefer it to other Javascript frameworks.</p>
<p>Batman.js advantages:</p>
<ul>
<li>Automatic URL generation based on model</li>
<li>HTML data-bind templates</li>
<li>Coffeescript</li>
</ul>
<p><a title="Cowboy: Erlang web server" href="https://github.com/extend/cowboy">Cowboy</a> is a newer Erlang web server that provides a REST handler based on <a title="Webmachine" href="https://github.com/basho/webmachine">Webmachine</a>. Both of these are perfect for developing a RESTful API, because they follow the HTTP standard exactly and when you are building an API based on HTTP, being able to properly reason about how the logic of the application maps to the protocol eases development and eases getting REST &#8220;right&#8221;.</p>
<h2>Nginx</h2>
<p>Any non-dynamic content should be served by <a title="Nginx" href="http://nginx.com/">Nginx</a> since there is no logic needed and it is something Nginx is great at, so why have Erlang do it? The snippet below configures Nginx to listen on port 80 and serve files from bcmvc&#8217;s <em>priv</em> directory. Each request is checked to see if it is a POST or any other method with a JSON request type. If either of those are true, the request is proxied on to a server listening on port 8080, in our case the Cowboy server.</p>
<pre style="color:#dcdccc;background-color:#3f3f3f;">server {
  listen 80;
  server_name localhost;

  location / {
    root   &lt;PATH TO CLONE&gt;/bcmvc/lib/bcmvc_web/priv/;

    <span style="color:#f0dfaf;font-weight:bold;">if</span> ($request_method ~* POST) {
      proxy_pass        http:<span style="color:#7f9f7f;">//</span><span style="color:#e0cf9f;font-weight:bold;text-decoration:underline;">localhost</span><span style="color:#7f9f7f;">:8080; </span>    }

    <span style="color:#f0dfaf;font-weight:bold;">if</span> ($http_accept ~* application/json) {
      proxy_pass        http:<span style="color:#7f9f7f;">//</span><span style="color:#e0cf9f;font-weight:bold;text-decoration:underline;">localhost</span><span style="color:#7f9f7f;">:8080; </span>    }
  }
}</pre>
<h2>The API</h2>
<p>Batman.js knows what endpoints to use and what data to send based on the name of the model we created and the encoded variables, <a title="Todo Model" href="https://github.com/tsloughter/bcmvc/blob/master/lib/bcmvc_web/priv/models/todo.coffee">code here</a>. This results in the following API:</p>
<table border="2" rules="groups" cellspacing="0" cellpadding="6">
<caption> </caption>
<col class="left" />
<col class="left" />
<col class="left" />
<col class="left" />
<thead>
<tr>
<th class="left" scope="col">Method</th>
<th class="left" scope="col">Endpoint</th>
<th class="left" scope="col">Data</th>
<th class="left" scope="col">Return</th>
</tr>
</thead>
<tbody>
<tr>
<td class="left">POST</td>
<td class="left"><em>todos</em></td>
<td class="left">{todo : {body:&#8221;bane wants to meet, not worried&#8221;,isDone:false}}</td>
<td class="left"></td>
</tr>
<tr>
<td class="left">PUT</td>
<td class="left">/todos/33e93b30-2371-4071-afc5-2d48226d5dba</td>
<td class="left">{todo : {body:&#8221;bane wants to meet, not worried&#8221;,isDone:false}}</td>
<td class="left"></td>
</tr>
<tr>
<td class="left">GET</td>
<td class="left"><em>todos</em></td>
<td class="left"></td>
<td class="left">[{todo : {id:"33e93b30-2371-4071-afc5-2d48226d5dba", body:"bane wants to meet, not worried", isDone:false}}]</td>
</tr>
<tr>
<td class="left">DELETE</td>
<td class="left">/todos/33e93b30-2371-4071-afc5-2d48226d5dba</td>
<td class="left"></td>
<td class="left"></td>
</tr>
</tbody>
</table>
<h2>Cowboy Dispatch and Supervisor</h2>
<p>Dispatch rules are matched by Cowboy to know what handler to send the request to. Here we have two rules. One that matches just the URL <em>/todos</em> and one that matches the URL with an additional element which will be associated with the atom <em>todo</em>. Both requests will be sent to the module <em>bcmvc_todo_handler</em>.</p>
<pre style="color:#dcdccc;background-color:#3f3f3f;">Dispatch = [{<span style="color:#cc9393;">'_'</span>, [{[&lt;&lt;<span style="color:#cc9393;">"todos"</span>&gt;&gt;], bcmvc_todo_handler, []},
                   {[&lt;&lt;<span style="color:#cc9393;">"todos"</span>&gt;&gt;, todo], bcmvc_todo_handler, []}]}],</pre>
<p>Cowboy provides a useful function <em>child_spec</em> for creating a child specfication to use in our supervisor. The child spec here tells Cowboy we want a TCP listener on port 8080 that handles the HTTP protocol. We additionally provide our dispatch list for it to match against and pass on requests.</p>
<pre style="color:#dcdccc;background-color:#3f3f3f;">ChildSpec = <span style="color:#8cd0d3;">cowboy</span>:<span style="color:#8cd0d3;">child_spec</span>(bcmvc_cowboy, 100, cowboy_tcp_transport, 
                              [{port, 8080}], cowboy_http_protocol, [{dispatch, <span style="color:#dfaf8f;">Dispatch</span>}]),</pre>
<h2>Cowboy Handler</h2>
<p>Now that we have a server on port 8080 that knows to send certain requests to our todo handler, we can build the module. The first required function to export is <em>init/3</em>. This function let&#8217;s Cowboy know we have a REST protocol, this is how it knows what functions to call (some have defaults and some existing in our module) to handle the request.</p>
<pre style="color:#dcdccc;background-color:#3f3f3f;"><span style="color:#8cd0d3;">init</span>(<span style="color:#dfaf8f;">_Transport</span>, <span style="color:#dfaf8f;">_Req</span>, <span style="color:#dfaf8f;">_Opts</span>) -&gt;
    {upgrade, protocol, cowboy_http_rest}.</pre>
<p>Knowing that this is a REST handler Cowboy will pass the request on to <em>allowed_methods/2</em> to find out if our handler is able to handle this method. Next, the content types accepted and provided by the handler are checked against the incoming request. The expected HTTP response status codes are returned if any of these fail. 405 for <em>allowed_methods</em>, XXX for <em>content_types_accepted</em> and XXX for <em>content_types_provided</em>.</p>
<pre style="color:#dcdccc;background-color:#3f3f3f;"><span style="color:#8cd0d3;">allowed_methods</span>(<span style="color:#dfaf8f;">Req</span>, <span style="color:#dfaf8f;">State</span>) -&gt;
    {[<span style="color:#cc9393;">'HEAD'</span>, <span style="color:#cc9393;">'GET'</span>, <span style="color:#cc9393;">'PUT'</span>, <span style="color:#cc9393;">'POST'</span>, <span style="color:#cc9393;">'DELETE'</span>], <span style="color:#dfaf8f;">Req</span>, <span style="color:#dfaf8f;">State</span>}.

<span style="color:#8cd0d3;">content_types_accepted</span>(<span style="color:#dfaf8f;">Req</span>, <span style="color:#dfaf8f;">State</span>) -&gt;
    {[{{&lt;&lt;<span style="color:#cc9393;">"application"</span>&gt;&gt;, &lt;&lt;<span style="color:#cc9393;">"json"</span>&gt;&gt;, []}, put_json}], <span style="color:#dfaf8f;">Req</span>, <span style="color:#dfaf8f;">State</span>}.

<span style="color:#8cd0d3;">content_types_provided</span>(<span style="color:#dfaf8f;">Req</span>, <span style="color:#dfaf8f;">State</span>) -&gt;
    {[{{&lt;&lt;<span style="color:#cc9393;">"application"</span>&gt;&gt;, &lt;&lt;<span style="color:#cc9393;">"json"</span>&gt;&gt;, []}, get_json}], <span style="color:#dfaf8f;">Req</span>, <span style="color:#dfaf8f;">State</span>}.</pre>
<p>Now the request is sent to the function that handles the HTTP method type of the request.</p>
<p>For a POST, a request to create a new todo item, the function <em>process_post/2</em> is sent the request. Here we retrieve the body, a JSON object, from the request, convert it to a record and save the model. We&#8217;ll see how this record conversion is done when we look at the model module. To inform the frontend of the id of our new resource we set the location header to be the path with the id.</p>
<pre style="color:#dcdccc;background-color:#3f3f3f;"><span style="color:#8cd0d3;">process_post</span>(<span style="color:#dfaf8f;">Req</span>, <span style="color:#dfaf8f;">State</span>) -&gt;
    {ok, <span style="color:#dfaf8f;">Body</span>, <span style="color:#dfaf8f;">Req1</span>} = <span style="color:#8cd0d3;">cowboy_http_req</span>:<span style="color:#8cd0d3;">body</span>(<span style="color:#dfaf8f;">Req</span>),
    <span style="color:#dfaf8f;">Todo</span> = <span style="color:#8cd0d3;">bcmvc_model_todo</span>:<span style="color:#8cd0d3;">to_record</span>(<span style="color:#dfaf8f;">Body</span>),
    <span style="color:#8cd0d3;">bcmvc_model_todo</span>:<span style="color:#8cd0d3;">save</span>(<span style="color:#dfaf8f;">Todo</span>),

    <span style="color:#dfaf8f;">NewId</span> = <span style="color:#8cd0d3;">bcmvc_model_todo</span>:<span style="color:#8cd0d3;">get</span>(id, <span style="color:#dfaf8f;">Todo</span>),
    {ok, <span style="color:#dfaf8f;">Req2</span>} = <span style="color:#8cd0d3;">cowboy_http_req</span>:<span style="color:#8cd0d3;">set_resp_header</span>(
                   &lt;&lt;<span style="color:#cc9393;">"Location"</span>&gt;&gt;, &lt;&lt;<span style="color:#cc9393;">"/todos/"</span>, <span style="color:#dfaf8f;">NewId</span>/binary&gt;&gt;, <span style="color:#dfaf8f;">Req1</span>),

    {true, <span style="color:#dfaf8f;">Req2</span>, <span style="color:#dfaf8f;">State</span>}.</pre>
<p>For this handler we expect PUT for an update to an object, that is what Batman.js does, but a PATCH would make more sense. For a PUT the URL contains the id for the todo item to be updated. That is retrieved with the<em> binding/2</em> function. The todo record is created the same as in <em>process_post/2</em> but then the this id is set for the model and the <em>update/1</em> function is used to save it to the database.</p>
<pre style="color:#dcdccc;background-color:#3f3f3f;"><span style="color:#8cd0d3;">put_json</span>(<span style="color:#dfaf8f;">Req</span>, <span style="color:#dfaf8f;">State</span>) -&gt;
    {ok, <span style="color:#dfaf8f;">Body</span>, <span style="color:#dfaf8f;">Req1</span>} = <span style="color:#8cd0d3;">cowboy_http_req</span>:<span style="color:#8cd0d3;">body</span>(<span style="color:#dfaf8f;">Req</span>),
    {<span style="color:#dfaf8f;">TodoId</span>, <span style="color:#dfaf8f;">Req2</span>} = <span style="color:#8cd0d3;">cowboy_http_req</span>:<span style="color:#8cd0d3;">binding</span>(todo, <span style="color:#dfaf8f;">Req1</span>),
    <span style="color:#dfaf8f;">Todo</span> = <span style="color:#8cd0d3;">bcmvc_model_todo</span>:<span style="color:#8cd0d3;">to_record</span>(<span style="color:#dfaf8f;">Body</span>),
    <span style="color:#dfaf8f;">Todo2</span> = <span style="color:#8cd0d3;">bcmvc_model_todo</span>:<span style="color:#8cd0d3;">set</span>([{id, <span style="color:#dfaf8f;">TodoId</span>}], <span style="color:#dfaf8f;">Todo</span>),
    <span style="color:#8cd0d3;">bcmvc_model_todo</span>:<span style="color:#8cd0d3;">update</span>(<span style="color:#dfaf8f;">Todo2</span>),    
    {true, <span style="color:#dfaf8f;">Req2</span>, <span style="color:#dfaf8f;">State</span>}.</pre>
<p>For a GET request, which for this application we do not deal with a request for a single todo item, all todo items are retrieved from the model module. Each of these is passed to the model&#8217;s <em>to_json/1</em> function and the result of converting each to JSON is combined into a binary string and placed between brackets so the Batman.js frontend receives a proper JSON list of JSON objects.</p>
<pre style="color:#dcdccc;background-color:#3f3f3f;"><span style="color:#8cd0d3;">get_json</span>(<span style="color:#dfaf8f;">Req</span>, <span style="color:#dfaf8f;">State</span>) -&gt;
    <span style="color:#dfaf8f;">JsonModels</span> = <span style="color:#8cd0d3;">lists</span>:<span style="color:#8cd0d3;">foldr</span>(<span style="color:#f0dfaf;font-weight:bold;">fun</span>(<span style="color:#dfaf8f;">X</span>, &lt;&lt;<span style="color:#cc9393;">""</span>&gt;&gt;) -&gt;
                                 <span style="color:#dfaf8f;">X</span>;
                            (<span style="color:#dfaf8f;">X</span>, <span style="color:#dfaf8f;">Acc</span>) -&gt;
                                 &lt;&lt;<span style="color:#dfaf8f;">Acc</span>/binary, <span style="color:#cc9393;">","</span>, <span style="color:#dfaf8f;">X</span>/binary&gt;&gt;
                         <span style="color:#f0dfaf;font-weight:bold;">end</span>, &lt;&lt;<span style="color:#cc9393;">""</span>&gt;&gt;, [<span style="color:#8cd0d3;">bcmvc_model_todo</span>:<span style="color:#8cd0d3;">to_json</span>(<span style="color:#dfaf8f;">Model</span>) <span style="color:#f0dfaf;font-weight:bold;">||</span> <span style="color:#dfaf8f;">Model</span> <span style="color:#f0dfaf;font-weight:bold;">&lt;-</span> <span style="color:#8cd0d3;">bcmvc_model_todo</span>:<span style="color:#8cd0d3;">all</span>()]),

    {&lt;&lt;<span style="color:#cc9393;">"["</span>, <span style="color:#dfaf8f;">JsonModels</span>/binary, <span style="color:#cc9393;">"]"</span>&gt;&gt;, <span style="color:#dfaf8f;">Req</span>, <span style="color:#dfaf8f;">State</span>}.</pre>
<p>And lastly, DELETE. Like in PUT the todo item&#8217;s id is retrieved from the bindings created based on the dispatch rules and this is passed to the model&#8217;s delete function.</p>
<pre style="color:#dcdccc;background-color:#3f3f3f;"><span style="color:#8cd0d3;">delete_resource</span>(<span style="color:#dfaf8f;">Req</span>, <span style="color:#dfaf8f;">State</span>) -&gt;
    {<span style="color:#dfaf8f;">TodoId</span>, <span style="color:#dfaf8f;">Req1</span>} = <span style="color:#8cd0d3;">cowboy_http_req</span>:<span style="color:#8cd0d3;">binding</span>(todo, <span style="color:#dfaf8f;">Req</span>),
    <span style="color:#8cd0d3;">bcmvc_model_todo</span>:<span style="color:#8cd0d3;">delete</span>(<span style="color:#dfaf8f;">TodoId</span>),
    {true, <span style="color:#dfaf8f;">Req1</span>, <span style="color:#dfaf8f;">State</span>}.</pre>
<h2>Models</h2>
<p>Model&#8217;s are repsented as records and must provide serialization functions to go between JSON and a record. Each model uses a parse transform that creates functions for creating and updating the record. The transform is a modified version of <a title="Parse Transforms" href="https://github.com/uwiger/parse_trans">exprecs</a> from Ulf Wiger that also uses the type definitions in the record to ensure when setting a field that it is the correct type. For example in the todo model <em>isDone</em> is a boolean, so when the model is created the boolean convert function will be matched to convert the string representation to an atom:</p>
<pre style="color:#dcdccc;background-color:#3f3f3f;"><span style="color:#8cd0d3;">convert</span>(boolean, &lt;&lt;<span style="color:#cc9393;">"false"</span>&gt;&gt;) -&gt;
    false;
<span style="color:#8cd0d3;">convert</span>(boolean, &lt;&lt;<span style="color:#cc9393;">"true"</span>&gt;&gt;) -&gt;
    true;</pre>
<p>So the key pieces of the<em> bcmvc_model_todo</em> are:</p>
<pre style="color:#dcdccc;background-color:#3f3f3f;"><span style="color:#8cd0d3;">-compile</span>({parse_transform, bcmvc_model_transform}).

<span style="color:#8cd0d3;">-record</span>(<span style="color:#8cd0d3;">bcmvc_model_todo</span>, {id = <span style="color:#8cd0d3;">ossp_uuid</span>:<span style="color:#8cd0d3;">make</span>(v1, text) :: <span style="color:#8cd0d3;">string</span>(),
                           body                          :: <span style="color:#8cd0d3;">binary</span>(),
                           isDone                        :: <span style="color:#8cd0d3;">boolean</span>()}).

<span style="color:#8cd0d3;">to_json</span>(<span style="color:#dfaf8f;">Record</span>) -&gt;
    ?<span style="color:#bfebbf;">record_to_json</span>(?<span style="color:#bfebbf;">MODULE</span>, <span style="color:#dfaf8f;">Record</span>).

<span style="color:#8cd0d3;">to_record</span>(<span style="color:#dfaf8f;">JSON</span>) -&gt;
    ?<span style="color:#bfebbf;">json_to_record</span>(?<span style="color:#bfebbf;">MODULE</span>, <span style="color:#dfaf8f;">JSON</span>).</pre>
<p>The<em> ?record_to_json</em> and <em>?json_to_record</em> macros are defined in <em>jsonerl.hrl</em>. These marcos are generic and work for any record that is typed and uses the model transform.</p>
<h2>Conclusion</h2>
<p>Clearly, much of what the resource handler and model do is generic and can be abstracted out so that implementing new models and resources can be even simpler. This is the goal of my project <a title="Maru" href="https://github.com/tsloughter/maru">Maru</a>. Currently it is based on Webmachine but is now being convered to Cowboy.</p>
<p>In the end, using Cowboy for building a RESTful interface for your application allows you to build interfaces for the frontend entirely separted from backend development, and if you want multiple interfaces (like native mobile and web), they both talk directly to the same backend. Also, from the beginning you have the option to open up your application with an API for other developers to take your application new places, and, shameless plug here, add your API to <a title="Mashape" href="http://www.mashape.com">Mashape</a> to spread your new app!</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/erlware.wordpress.com/676/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/erlware.wordpress.com/676/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.erlware.org&#038;blog=19876286&#038;post=676&#038;subd=erlware&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://blog.erlware.org/2012/04/30/cowboy-and-batman-js-for-erlang-web-development/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
	
		<media:content url="http://2.gravatar.com/avatar/e9f10146ae0cd7082107b227598f56c2?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">kungfooguru</media:title>
		</media:content>
	</item>
		<item>
		<title>Erlang, Cowboy and Batman.js for Building Web Applications</title>
		<link>http://blog.erlware.org/2012/04/27/erlang-cowboy-and-batman-js-for-building-web-applications/</link>
		<comments>http://blog.erlware.org/2012/04/27/erlang-cowboy-and-batman-js-for-building-web-applications/#comments</comments>
		<pubDate>Fri, 27 Apr 2012 15:11:28 +0000</pubDate>
		<dc:creator>Tristan Sloughter</dc:creator>
				<category><![CDATA[Talks]]></category>
		<category><![CDATA[API]]></category>
		<category><![CDATA[batman.js]]></category>
		<category><![CDATA[coffeescript]]></category>
		<category><![CDATA[Cowboy]]></category>
		<category><![CDATA[Erlang]]></category>
		<category><![CDATA[Javascript]]></category>
		<category><![CDATA[RESTful]]></category>
		<category><![CDATA[Web]]></category>

		<guid isPermaLink="false">http://blog.erlware.org/?p=662</guid>
		<description><![CDATA[I&#8217;ll have a complete walk of through using Cowboy and Batman.js to build the TodoMVC clone in a few days. For now I have the slides from my talk at the Chicago Erlang User Group: Chicago Erlang User Group April, 4th 2012 I couldn&#8217;t get iframe embedding to work with WordPress&#8230; So if anyone knows [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.erlware.org&#038;blog=19876286&#038;post=662&#038;subd=erlware&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>I&#8217;ll have a complete walk of through using <a title="Cowboy, Erlang web server" href="https://github.com/extend/cowboy">Cowboy</a> and <a title="Batman.js, Coffeescript MVC Framework" href="http://batmanjs.org/">Batman.js</a> to build the TodoMVC clone in a few days. For now I have the slides from my talk at the Chicago Erlang User Group:</p>
<p><a href='http://tsloughter.github.com/ceug_4_2012/#1'>Chicago Erlang User Group April, 4th 2012</a></p>
<p>I couldn&#8217;t get iframe embedding to work with WordPress&#8230; So if anyone knows what that is up with please comment.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/erlware.wordpress.com/662/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/erlware.wordpress.com/662/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.erlware.org&#038;blog=19876286&#038;post=662&#038;subd=erlware&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://blog.erlware.org/2012/04/27/erlang-cowboy-and-batman-js-for-building-web-applications/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://2.gravatar.com/avatar/e9f10146ae0cd7082107b227598f56c2?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">kungfooguru</media:title>
		</media:content>
	</item>
		<item>
		<title>Erlang/OTP Release Structure</title>
		<link>http://blog.erlware.org/2012/01/23/erlangotp-release-structure/</link>
		<comments>http://blog.erlware.org/2012/01/23/erlangotp-release-structure/#comments</comments>
		<pubDate>Mon, 23 Jan 2012 16:34:39 +0000</pubDate>
		<dc:creator>Eric B Merritt</dc:creator>
				<category><![CDATA[Erlang]]></category>

		<guid isPermaLink="false">http://blog.erlware.org/?p=653</guid>
		<description><![CDATA[How to organize Erlang/OTP releases over on my personal blog. Worth reading if you are in the process of figuring out how to manage Erlang in your organization.<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.erlware.org&#038;blog=19876286&#038;post=653&#038;subd=erlware&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p><a href="http://ericbmerritt.posterous.com/95700741" title="The Blog Post">How to organize Erlang/OTP releases</a> over on my personal blog. Worth reading if you are in the process of figuring out how to manage Erlang in your organization.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/erlware.wordpress.com/653/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/erlware.wordpress.com/653/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.erlware.org&#038;blog=19876286&#038;post=653&#038;subd=erlware&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://blog.erlware.org/2012/01/23/erlangotp-release-structure/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/1c32ef01b258b3b5ca43d8da88653fb4?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">cyberlync</media:title>
		</media:content>
	</item>
	</channel>
</rss>
