<?xml version="1.0" encoding="UTF-8" ?>

<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
  <channel>
   
    <title>thebhwgroup.com</title>
   
   <link>https://thebhwgroup.com</link>
   <description>We build web and mobile applications for businesses of all sizes.
</description>
   <language>en-us</language>
   <managingEditor>bhwinfo@thebhwgroup.com</managingEditor>
   <atom:link href="rss" rel="self" type="application/rss+xml" />
   
    
	  <item>
        <title>Website Design with Clojure and Reagent</title>
        <link>https://thebhwgroup.com/blog/2015/03/website-dev-clojure-reagent</link>
		<author>Brett Burnett</author>
		<pubDate>2015-03-16T00:00:00+00:00</pubDate>
		<guid isPermaLink="true">https://thebhwgroup.com/blog/2015/03/website-dev-clojure-reagent</guid>
		<description><![CDATA[
		   ##Website Design and Development in Reagent

Welcome to our third article discussing <a href="https://thebhwgroup.com/services/website-design-company-austin-texas" target="_blank">website design</a> and development in [Clojure](http://clojure.org).  Clojure is an exciting Lisp language that offers full-stack web development, compiling to the JVM for server execution and to JavaScript for client side execution.  In our first article we presented [Clojure](https://thebhwgroup.com/blog/2014/08/single-page-applications-clojure-couchdb) as a server-side programming language by demonstrating a simple REST API for a Single Page Application (SPA).  In our second article we demonstrated <a href="https://thebhwgroup.com/blog/2014/09/react-angularjs-om-spa" target="_blank">Om</a>, a popular client-side scripting framework using ClojureScript and React.  Today we look at <a href="http://holmsand.github.io/reagent" target="_blank">Reagent</a>, a second philosophy to client-side web development in Clojure.

{% include full-blog-image.html src="clojure_logo.png" alt="Clojure logo" %}

##Why Reagent?

Reagent is a ClojureScript library that provides a programming and templating interface for Facebook's <a href="http://facebook.github.io/react" target="_blank">React</a> library.  Why does the Clojure community need a second client-side framework targeting React?  To answer that question, you have to consider React's history.  React's early releases required the use of a proprietary API that generated HTML and did not use traditional markup language.  In React's API, HTML DOM elements are constructed from similarly named React API functions.  React is a novel way to synchronize client-side state and the DOM, but with an already steep learning curve, Facebook decided that the API added too much additional complexity for newcomers.  In order to spur adoption, and partly remove the need to learn React's proprietary API, Facebook created a second method to integrate with React using familiar HTML templates via a JavaScript langauage extension, <a href="http://facebook.github.io/react/docs/jsx-in-depth.html" target="_blank">JSX</a>.  Today Facebook recommends React developers use JSX instead of the React API.

Om was released before Reagent and targets React's API instead of JSX.  Developers must learn the React API to program Om.  Reagent was released after Om and targets JSX instead of the React API.  This means that programming in Reagent is immediately familiar to developers who know HTML.  Learning the React API is not necessary in Reagent.

{% include full-blog-image.html src="react_logo.png" alt="React logo" %}

##Reagent and Om Compared

To demonstrate the differences between Om and Reagent we will build a small example component.  We'll create a simple component that should display the current time in the following HTML structure.

```html
<div class='time-component'>
  <h3 class='time-title'>The current time is:</h3>
  <p class='time'>{% raw %}{{24 hour time format}}{% endraw %}</p>
</div>
```


###Similarities
Both frameworks start by rendering their component into an existing DOM element specified by an ID.  A typical HTML setup for both frameworks would look like the following:

```html
<div id='simple-component'></div>
```

Om wires up our "simple-component" and renders content into this element as follows:

```clojure
(om/root simple-component app-state
    {:target (. js/document (getElementById "simple-component"))}))
```

Reagent's wire up is very similar, but slightly more compact:

```clojure
(reagent/render-component [simple-component] (.getElementById js/document "simple-component")))
```

###Where they differ
From here the two frameworks diverge, first we'll show Om's approach to implementing our "simple-component".

```clojure
(def app-state
  (atom
   {:current-time (js/Date.)}))

(defn simple-component [app owner]
  (reify
    om/IWillMount
    (will-mount [this]
                (js/setInterval #(om/update! app [:current-time] (js/Date.)) 1000))
    om/IRender
    (render [this]
            (let [time-str (-> (:current-time app) .toTimeString (clojure.string/split " ") first)]
              (dom/div #js {:className "time-component"}
                       (dom/h3 #js {:className "time-title"} "The current time is:")
                       (dom/p #js {:className "time"} time-str))))))
```

Here our Om code uses the React API Lifecycle to setup a JavaScript interval that updates our app state every second.  Om uses a single shared app state between all components which in our example is called "app-state" and contains the key "current-time".  Om manages app-state through clojure atoms which provide managed access to synchronous state.  Now the equivalent Reagent implementation:

```clojure
(defn simple-component []
  (let [current-time (atom (js/Date.))]
    (fn []
      (js/setTimeout #(reset! current-time (js/Date.)) 1000)
      (let [time-str (-> @current-time .toTimeString (clojure.string/split " ") first)]
        [:h3.time-title "The current time is:"]
        [:p.time time-str]))))
```

Our Reagent source code closely resembles a typical HTML document, which is immediately more comfortable for web developers with limited React API experience.  In our opinion the Reagent code is more concise and compact while being easier to read.  Some of the syntax complexity in Om comes from its dependence on the clojure <code>reify</code> macro to create a component which implements the React Lifecycle API.  Reagent hides this detail from the developer by handling the API interface for the user.  In our example, Reagent is able to use the <code>setTimeout</code> event instead of <code>setInterval</code> because our Reagent component returns a function for rendering instead of the actual rendered result.  Each time the component is rendered in Reagent we set a new timer.  Our Om code only wires up once in the <code>IWillMount</code> API interface so we use <code>setInterval</code> to ensure we continue to fire updates every second.

In addition to the syntax and API differences, Reagent and Om take a very different approach to state management.  Instead of following the global app state approach like Om, Reagent uses its own implementation of the atom class which re-renders dependent components based on an atom being dereferenced.  This approach allows Reagent to use local component atoms for state information that isn't shared with other components.  Our example makes use of this local state feature by declaring our current-time as an atom within the Reagent component itself.

Now that we're covered some of the differences, let's go step by step in creating a new Reagent project using Leinengen.

##Starting a Reagent Project

In this article we'll continue to use the <a href="https://thebhwgroup.com/blog/2014/09/bi-nodejs-couchdb-mapreduce" target="_blank">2014 World Cup datasource</a> shown in the prior two articles.  To start our Reagent example we first use a Leinengen template, <a href="https://github.com/reagent-project/reagent-template" target="_blank">reagent-template</a>.

```bash
lein new reagent <name> +test
```

Second, we make a few changes to the project files to include our dependencies, including <a href="https://github.com/clojure-clutch/clutch" target="_blank">clutch</a> for accessing <a href="http://couchdb.apache.org" target="_blank">CouchDB</a>.

{% include full-blog-image.html src="couchdb-logo.jpg" alt="CouchDB logo" %}

```clojure
[ring/ring-json "0.3.1"]
[com.ashafa/clutch "0.4.0"]
```

Third step, we need to change our ring middleware and include our module.  Check the  <a href="https://github.com/bhw/clojure-reagent" target="_blank">GitHub repo</a> for the complete source.  The most interesting changes happen around the construction of our ring middleware.  The sample below shows how to use the closure threading macro <code>-></code> to wrap our middleware and our JSON handlers around the request.

```clojure
(def app
  (-> (handler/api app-routes)
      (middleware/wrap-json-body)
      (middleware/wrap-json-response)))
```

Finally we start our development server and figwheel, which will start a REPL with ClojureScript and automatically compile and update our client code when we make changes to the files.

```bash
lein figwheel
```

and we get...

```bash
java.lang.NoClassDefFoundError: org/apache/http/pool/ConnPoolControl, compiling:(com/ashafa/clutch/http_client.clj:1:1)
  at clojure.lang.Compiler.load(Compiler.java:7142)
  at clojure.lang.RT.loadResourceScript(RT.java:370)
  at clojure.lang.RT.loadResourceScript(RT.java:361)
...
Caused by: java.lang.ClassNotFoundException: org.apache.http.pool.ConnPoolControl
  at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
...
```

This error indicates that we have dependency conflicts.  Leinengen gives us a handy tool to diagnose these issues, <code>deps :tree</code>.
Deps will print out a project's dependencies in a tree form, and most importantly, will show conflicts at the top of the output.

```bash
lein deps :tree
```

```bash
Possibly confusing dependencies found:
[com.ashafa/clutch "0.4.0"] -> [clj-http "0.5.5"]
 overrides
[leiningen "2.5.1"] -> [clj-http "0.9.2" :exclusions [crouton]]
...
[com.ashafa/clutch "0.4.0"] -> [clj-http "0.5.5"] -> [org.apache.httpcomponents/httpclient "4.2.1"]
 overrides
[leiningen "2.5.1"] -> [clj-http "0.9.2" :exclusions [crouton]] -> [org.apache.httpcomponents/httpmime "4.3.3" :exclusions [org.clojure/clojure]] -> [org.apache.httpcomponents/httpclient "4.3.3"]
 and
[leiningen "2.5.1"] -> [leiningen-core "2.5.1"] -> [org.apache.maven.wagon/wagon-http "2.7"] -> [org.apache.httpcomponents/httpclient "4.3.5"]
 and
[leiningen "2.5.1"] -> [clj-http "0.9.2" :exclusions [crouton]] -> [org.apache.httpcomponents/httpclient "4.3.3" :exclusions [org.clojure/clojure]]
```

##Correcting Dependencies

Resolving conflicts requires study, and in our case we can force clojure to use the latest libraries for httpclient and clj-http.  These are API compatible with the version clutch links.  To correct these dependency conflicts we need to help clojure's compiler figure out what to do.  First, we'll move clutch to the bottom of our dependency list and then we'll add these two dependency overrides.

```clojure
[com.ashafa/clutch "0.4.0"]
[org.apache.httpcomponents/httpclient "4.3.5"]
[clj-http "0.9.2" :exclusions [crouton]]
[cljs-ajax "0.3.10"]]
```

Now we're ready to start our server again with <code>lein figwheel</code>

```bash
Figwheel: Starting server at http://localhost:3449
Focusing on build ids: app
Compiling "resources/public/js/app.js" from ["src/cljs" "env/dev/cljs"]...
Successfully compiled "resources/public/js/app.js" in 12.159 seconds.
Started Figwheel autobuilder see: figwheel_server.log

Launching ClojureScript REPL for build: app
Figwheel Controls:
          (stop-autobuild)           ;; stops Figwheel autobuilder
          (start-autobuild [id ...]) ;; starts autobuilder focused on optional ids
          (switch-to-build id ...)   ;; switches autobuilder to different build
          (reset-autobuild)          ;; stops, cleans, and starts autobuilder
          (build-once [id ...])      ;; builds source once time
          (clean-build [id ..])      ;; deletes compiled cljs target files
          (add-dep [org.om/om "0.8.1"]) ;; add a dependency. very experimental
  Switch REPL build focus:
          :cljs/quit                 ;; allows you to switch REPL to another build
    Docs: (doc function-name-here)
    Exit: Control+C or :cljs/quit
 Results: Stored in vars *1, *2, *3
Prompt will show when figwheel connects to your application
To quit, type: :cljs/quit
```

##Conclusion
React is an exciting client-side framework that we use on many new projects.  Reagent makes React more accessible to Clojure developers who don't know React's API.  We feel that our Reagent code is easier to read than our Om code, especially for deeper DOM trees.  Reagent's advantages over Om stem from adopting the same strategy Facebook has taken with React's JSX interface.  Be sure to check out the entire project's source on <a href="https://github.com/bhw/clojure-reagent" target="_blank">GitHub</a>.  Our next article will be out in a few weeks and will compare the performance between SPA's built with Angular, React, JavaScript, and Clojure.

<p align="center"><em>Do you need an expert in web development? With a team of web development specialists covering a wide range of skill sets and backgrounds, <a href="https://thebhwgroup.com/services/web-application-development-company-austin-texas" target="_blank">The BHW Group</a> is prepared to help your company make the transformations needed to remain competitive in today’s high-tech marketplace.</em></p>
		]]></description>

    
        <category>clojure</category>
    
        <category>couchdb</category>
    
        <category>json</category>
    
        <category>rest</category>
    
        <category>reagent</category>
    
    
        <category>Development</category>
    

	  </item>
    
	  <item>
        <title>Single Page Applications with Clojure and CouchDB</title>
        <link>https://thebhwgroup.com/blog/2014/08/single-page-applications-clojure-couchdb</link>
		<author>Brett Burnett</author>
		<pubDate>2014-08-05T00:00:00+00:00</pubDate>
		<guid isPermaLink="true">https://thebhwgroup.com/blog/2014/08/single-page-applications-clojure-couchdb</guid>
		<description><![CDATA[
		   ##Single Page Application Overview

The single page application (SPA) approach has revolutionized our approach to development.  Fantastic client-side Javascript frameworks like [AngularJS](https://angularjs.org/), [Knockout](http://knockoutjs.com/), and [React](http://facebook.github.io/react/) have made the transition easy and fun.  As we’ve written more and more SPAs an unexpected trend has emerged.  We’ve moved to a *thin server architecture* for delivering our back-end solutions on SPA projects.  We increasingly think of the application tier as plumbing, only responsible for data storage with a little authentication, authorization, and validation thrown in.

We’ve built thin SPA back-ends in Microsoft ASP.Net MVC, ASP.Net Web API, NodeJS with Express, and Ruby with Sinatra and Rails.  As the back-end has lost logic and responsibilities we care less and less about which technology stack we select for the solution.  Having covered three of the biggest interpreted runtimes in the CLR, V8, and Ruby, we recently wanted to deliver a back-end solution for the JVM.  We reviewed many options like jRuby and Scala, but selected Clojure.  We feel Clojure's functional programming and data structure philosophy are a better match for our style of thin server architectures.  Clojure checks the box as a solution we can deploy on the JVM, and in this article we’ll explore our experience building a simple API to store and load JSON documents.

As an added benefit, Clojure’s immutable data structure philosophy has influenced [Om](https://github.com/swannodette/om), a high-performance client-side rendering framework based on React.  In our second article we’ll demonstrate a simple SPA using Om building upon the Clojure JSON REST API presented here.

##CouchDB
We wanted the data storage back-end for this example to complement Clojure’s focus on data-structures.  As a document store, [CouchDB](http://couchdb.apache.org/) fits nicely in our example since it maps directly to and from Clojure’s lists, sets, and maps.  Just as single page applications have reduced our application-tier complexity, they have also changed our approach to data modeling.  Our SPA front-end is based on Javascript, and as a dynamic language, Javascript is far more accepting and malleable to change in our business data models.  SPAs have freed us from statically typed rendering logic and boiler plate domain to data transfer object (DTO) mapping code.  We’ll discuss light-weight data modeling more in a future article.

##Getting Started
Let’s get started with the project.  First we need some prerequisites: Leiningen, JDK, CouchDB, and a Clojure-friendly editor.  We selected [Light Table](http://www.lighttable.com/) as our editor and have been pretty happy with it so far.  We started with a default Ring server running on Jetty and updated our project.clj to include several Clojure libraries (compojure, ring-json, ring-core, and clutch):

```clojure
:dependencies [ [org.clojure/clojure "1.6.0"]
               [compojure "1.1.8"]
               [ring/ring-core "1.2.1"]
               [ring/ring-json "0.3.1"]
               [com.ashafa/clutch "0.4.0-RC1"] ]
```

Clutch wraps the CouchDB interface for easy consumption in Clojure.  We decided to use the “experimental” interface, but since it hasn’t been actively developed since 2012 we may switch back to the main Clutch API…

Next modify your handler.clj file so the require sections reads like so:

```clojure
(:require [compojure.core :refer :all]
          [compojure.handler :as handler]
          [compojure.route :as route]
          [ring.middleware.json :as middleware]
          [ring.util.response :refer [resource-response response]]
 )
```

We then define two routes:

```clojure
 (GET
   ["/test/:id" :id #"[0-9]{1,4}"] [id]
   (load-record id))

 (POST "/"
   {body :body}
   (save-record body))
```

We also changed our app to wrap some middleware around Ring.  With this change we can receive JSON as the body of an HTTP POST.

```clojure
(def app
 (-> (handler/api app-routes)
 (middleware/wrap-json-body)
 (middleware/wrap-json-response)))
```

In our methods.clj file we added the following:

```clojure
(ns firstweb.views)
(require '[com.ashafa.clutch :as clutch])

(defn open-connection []
  (let [conn (doto
               (clutch/couch "test")
               (clutch/create!))]
    conn))

(def db-connection (delay (open-connection)))

(defn db [] @db-connection)

(defn load-record
  [id]
  {:body (get-in (db) [id])})

(defn save-record
  [data]
  (let [id (get-in data ["_id"])]
    (clutch/assoc! (db) id data)
    {:body (get-in (db) [id])}))
```

##Launch our Single Page Application back-end

With this code in place we fire up our server in leiningen and then proceeded to construct a post via Postman:

{% include full-blog-image.html src="postman-send.png" alt="Sending JSON REST API Request with Postman" %}

And our response:

{% include full-blog-image.html src="postman-resp.png" alt="Single Page Application JSON REST API Response" %}

Now we can request the JSON from our Clojure WEP API via an HTTP GET, shown from Google Developer Tools:

{% include full-blog-image.html src="dev-tools-resp.png" alt="Single Page Application Google Developer Tools Response" %}

##Futon
Before we finish we thought it would be great to throw out a mention on CouchDB’s fantastic Web UI explorer, Futon.  Futon allows us to browse and make changes to our CouchDB data, as well as construct map-reduce results.  Here are some screenshots showing it in action:

{% include full-blog-image.html src="futon-1.png" alt="Single Page Application CouchDB Futon Document" %}

Now for a quick map-reduce to find the total goals scored in our incomplete sample 2014 World Cup results:

{% include full-blog-image.html src="futon-2.png" alt="Single Page Application CouchDB Futon Map-Reduce" %}

##Conclusion
We hope you have enjoyed a quick overview of using Clojure and CouchDB as a back-end for a Single Page Application. In our next article we will demonstrate how Om and ClojureScript can be used in the SPA client to create some incredible performance gains for complex rendering scenarios.

<p align="center"><em>Do you need an expert in web development? With a team of web development specialists covering a wide range of skill sets and backgrounds, <a href="https://thebhwgroup.com/services/web-application-development-company-austin-texas" target="_blank">The BHW Group</a> is prepared to help your company make the transformations needed to remain competitive in today’s high-tech marketplace.</em></p>
		]]></description>

    
        <category>clojure</category>
    
        <category>couchdb</category>
    
        <category>json</category>
    
        <category>rest</category>
    
    
        <category>Development</category>
    

	  </item>
    
  </channel>
</rss>
