35,99 €
This book is for anyone who's worked with Clojure and wants to use it to start developing applications for the Web. Experience or familiarity with basic Clojure syntax is a must, and exposure to Leiningen (or other similar build tools such as Maven) would be helpful.
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 254
Veröffentlichungsjahr: 2015
Copyright © 2015 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
First published: February 2015
Production reference: 1180215
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham B3 2PB, UK.
ISBN 978-1-78439-222-2
www.packtpub.com
Author
Ryan Baldwin
Reviewers
Eduardo Díaz
Shu Wang
Nate West
Daniel Ziltener
Commissioning Editor
Usha Iyer
Acquisition Editor
Neha Nagwekar
Content Development Editor
Rohit Kumar Singh
Technical Editors
Prajakta Mhatre
Rohith Rajan
Copy Editors
Pranjali Chury
Veena Mukundan
Vikrant Phadke
Project Coordinator
Mary Alex
Proofreaders
Ting Baker
Maria Gould
Indexer
Mariammal Chettiyar
Graphics
Disha Haria
Abhinash Sahu
Production Coordinator
Manu Joseph
Cover Work
Manu Joseph
Ryan Baldwin is a theatre major turned computer science geek. Hailing from the prairies of Western Canada, Ryan has been developing software on a wide array of platforms and technologies since 2001. Once, he wrote a crazy system application that compiled XSD Schema Docs into XAML forms that performed two-way binding with underlying XML documents in .NET WPF. Why? Because it had to be done. Another time, he worked on a project that mashed many social networks into one gigantic thing that essentially allowed users to find out all of their indirect connections. It was eventually shelved.
In 2012, he relocated to Toronto, where he works with the University Health Network, developing systems and tools that facilitate patient information exchange. You can often find him wearing headphones and jittering in coffee shops.
I'd like to thank Packt for giving me this opportunity and Dmitri Sotnikov for pushing me to do it. Without either of you, I probably would have gotten a lot more sleep and a lot less experience out of life. I'd also like to thank Chris Kay Fraser, without whose support and vegan brownies I would have never had the confidence to pursue such a project. I'd finally like to thank my family, friends, colleagues, and anybody else who interacted with me over these past several months; I'll buy you a "thank you" beer for putting up with me. All my reviewers who took the time to read, recheck, and provide essential feedback, I owe all of you at least a pitcher of beer (hit me up next time you're in Toronto). And, of course, I'd like to thank you, dear readers; without you, none of this would have happened. I am both humbled and terrified of you.
Eduardo Díaz is a Java developer, with experience particularly in web development. He has been interested in finding new programming paradigms and languages since he started developing software.
Clojure (and functional programming with Clojure) caught Eduardo's attention as an excellent mixture of a very unique paradigm and a pragmatic approach to programming. He has used it to build a data collection platform for several high-traffic sites, similar to Google Analytics. Clojure was an excellent choice for him, because it minimized errors and development time.
Writing this book was an incredible idea! More developers need to know the power of Clojure and how it can make their lives better. Thank you Ryan Baldwin and everyone involved in making this book happen!
Nate West is a polyglot web developer based in Nashville, Tennessee. While he has yet to meet a language he doesn't like, he found his home in the land of Lisp. As a developer at Blue Box, he gets paid to write in Ruby. When not learning new languages, he enjoys hanging out with his wife, playing with his dog, philosophizing over a cup of coffee, and mentoring at Nashville Software School.
Daniel Ziltener was born in the canton of Bern in Switzerland. He started programming at the age of 10 and acquired broad general knowledge about programming and software engineering, including desktop and web development and the programming languages such as Java, C++, Scala, Clojure, and Scheme. He started his studies in computer science at the University of Bern in 2012. Since then, he has worked as a Clojure software developer at the university's historical institute.
I'd like to thank the awesome Clojure community for all the great libraries and their support, especially in #Clojure, while I was learning Clojure a few years ago—it's been since 1.3! I'd also like to thank my employer for regularly giving me time off to review this book. You all really enabled me to become a Clojure pro.
For support files and downloads related to your book, please visit www.PacktPub.com.
Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at <[email protected]> for more details.
At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.
https://www2.packtpub.com/books/subscription/packtlib
Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can search, access, and read Packt's entire library of books.
If you have an account with Packt at www.PacktPub.com, you can use this to access PacktLib today and view 9 entirely free books. Simply use your login credentials for immediate access.
Clojure is a beautiful, concise language, and its adoption for web applications is ready and about to explode. In Clojure Web Development Essentials, you will learn how to build a Clojure web application from scratch using the Leiningen build tool and the Luminus application template. We'll start by creating a simple example application in the first few pages of the first chapter, and build on that application with each subsequent chapter. We'll cover URL routing, template rendering, database connectivity, form validation, and everything else we need to build a typical web app. By the end of this book, you'll have the knowledge required to venture into the world of web development, and you'll be able to use your skills for the betterment of the Internet.
Chapter 1, Getting Started with Luminus, guides you through creating a new project using the Luminus application template. We'll then dive into what was generated, what the out-of-the-box project dependencies are, and the general file structure of a Luminus web app.
Chapter 2, Ring and the Ring Server, describes the core technologies driving our application, and shows you how to use the development web server.
Chapter 3, Logging, demonstrates configuration of some basic logging and the Clojure logging library, Timbre.
Chapter 4, URL Routing and Template Rendering, starts to dive into the important part of web applications. It shows you how to handle incoming requests using Compojure, and how to render web pages using the Selmer templating engine. We'll also create a sign-up form for our application.
Chapter 5, Handling Form Input, teaches you how to validate form data and report form validation errors back to the user.
Chapter 6, Testing in Clojure, is a quick tour of automated testing and its use in Clojure.
Chapter 7, Getting Started with the Database, is the first of three chapters covering database management and interactivity. We'll set up our application's database, and you will learn how to manage your database schema using the Migratus Leiningen plug. Then we will store the form input created in the fifth chapter using YeSQL.
Chapter 8, Reading Data from the Database, continues exploring database interactivity by teaching you how to retrieve data from the database using YeSQL. We'll then create a couple of new web pages that list the most recently added items in our database.
Chapter 9, Database Transactions, gives us a brief overview of what database transactions are. We'll then create a form that transactionally inserts data into multiple tables.
Chapter 10, Sessions and Cookies, demonstrates how sessions and cookies are managed and maintained in Noir. We'll then create an authentication form for our application, and save a cookie in the user's browser to remember their username the next time they log in.
Chapter 11, Environment Configuration and Deployment, guides us through abstracting our environment configuration (such as database connectivity) and describes a few common ways by which we can deploy our application.
Appendix, Using Korma – a Clojure DSL for SQL, covers the modification of the YeSQL model layers to use Korma, a native Clojure Domain Specific Language that can be used to interact with the database if you're not keen on using raw SQL.
First and foremost, you must be familiar with the Clojure programming language. You'll also need to install the Leiningen build tool. Familiarity with basic web technology is also valuable.
This book targets software developers who are already using Clojure but want to use their skill set for web applications. Very little of this book does any fancy frontend development, and most of it focuses on server-side development. If you're primarily a frontend developer, or have never heard of Clojure, this book is precisely not what you are looking for.
In this book, you will find a number of styles of text that distinguish between different kinds of information. Here are some examples of these styles and explanations of their meanings.
Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: "We can include other contexts through the use of the include directive."
A block of code is set as follows:
When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:
Any command-line input or output is written as follows:
New terms and important words are shown in bold. Words that you see on the screen, in menus or dialog boxes for example, appear in the text like this: "clicking the Next button moves you to the next screen."
Warnings or important notes appear in a box like this.
Tips and tricks appear like this.
Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or may have disliked. Reader feedback is important for us to develop titles that you really get the most out of.
To send us general feedback, simply send an e-mail to <[email protected]>, and mention the book's title via the subject of your message.
If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.
Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.
You can download the example code files from your account at http://www.packtpub.com for all the Packt Publishing books you have purchased. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.
Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the ErrataSubmissionForm link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title. Any existing errata can be viewed by selecting your title from http://www.packtpub.com/support.
Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.
Please contact us at <[email protected]> with a link to the suspected pirated material.
We appreciate your help in protecting our authors and our ability to bring you valuable content.
If you have a problem with any aspect of this book, you can contact us at <[email protected]>, and we will do our best to address the problem.
Ah, getting started! This chapter introduces you to the foundations of Clojure web development using Luminus, a popular web application template for Leiningen. In this chapter, you will:
In this chapter, we'll create a new web application called hipstr, an application that will help us track our vinyl collection and endow us with obscure credibility. We'll build this application with each subsequent chapter by creating our own route handlers, interacting with a database, authenticating users, validating form input, and reading/writing cookies. By the end of this book, we'll know the Clojure web basics well enough that we'll be wearing plaid shirts and sipping bourbon aged in casks from a place nobody's ever heard of.
Our project will rely heavily on Leiningen, a build and task tool for Clojure. Leiningen allows us to easily maintain our application's dependencies, assists us in common tasks such as database migrations, running tests, producing binaries (jars and wars), and a plethora of other things. Leiningen is akin to Java's build tool Maven (http://maven.apache.org), and Ruby's Rake (http://github.com/jimweirich/rake). As Leiningen's web page (http://leiningen.org) concisely puts it: for automating Clojure projects without setting your hair on fire.
If you haven't already installed Leiningen 2.x, head over to http://leiningen.org/#install and follow the four simple instructions. It will take just 60 seconds, and the world of Clojure will become your oyster.
After you've installed Leiningen, you'll have access to a new command in your terminal, lein. Invoking this command will invoke Leiningen.
The basic makeup of a Leiningen task can be summarized as follows:
In the preceding shell pseudo-command, we invoke Leiningen using its binary. The lein$TASK argument is the Leiningen task we want to execute (such as install, jar, etc.), and $TASK_ARGUMENTS is any information required for that task to do its job, including additional subtasks and the arguments for a given subtask. You can see a full list of the available tasks in Leiningen by executing the following command:
You can also view the help content for a specific Leiningen task by executing the following command:
You can use these commands whenever you need to know how to do something in Leiningen.
Leiningen can generate an application skeleton (or scaffolding) from a plethora of different templates. There's a template for nearly everything such as clojurescript projects, web applications (of course), and much more.
To generate a new application, we use the new Leiningen task whose basic syntax is as follows:
The new task expects, at a minimum, a name for the project ($PROJECT_NAME). Optionally, we can provide a specific template to use ($TEMPLATE_NAME). If we don't specify a template, then lein will use the default template, which is a general template for developing libraries.
For our project we'll use the Luminus template, an excellent template for web applications. Luminus generates a project and wires in the libraries to support pretty much every aspect of web development including sessions, cookies, route handling, and template rendering.
At the time of this writing, the Luminus template was at version 1.16.7. To ensure the code examples in this book work, you can force Leiningen to use a specific version of Luminus by modifying Leiningen's profiles.clj file (typically found in your home directory, in a folder called .lein) to include the specific version of Luminus. For example:
This modification will ensure that version 1.16.7 of the Luminus template is used when generating a Luminus-based application.
Just try the following command:
Downloading the example code
You can download the example code files for all Packt books you have purchased from your account at http://www.PacktPub.com. If you purchased this book elsewhere, you can visit http://www.PacktPub.com/support and register to have the files e-mailed directly to you.
The preceding command will generate a fully runnable application in a directory called hipstr. You can run the application by using cd hipstr to enter into the hipstr directory and then execute the following command:
In the preceding command line, the lein ring server command updates our class path with the dependencies required to compile and run the app. It then launches the development server (an embedded Jetty server) and starts serving on port 3000. Lastly, it launches our default web browser and navigates to the root page.
In the preceding example, ring is the Leiningen task, and server is the ring subtask. You can view a full list of ring subtasks by entering the lein help ring command in your terminal.
The subsequent output of lein ring server is a series of debug statements that lets us know what the heck is going on during the startup process. Any generated exceptions or problems that occur while attempting to launch the application will be emitted as part of this output.
If anything doesn't go as planned, or you're stumped and confused, feel free to check the Luminus documentation at http://www.luminusweb.net. You can also get some help from people in the Luminus community (https://groups.google.com/forum/?fromgroups#!forum/luminusweb) or the Ring community (https://groups.google.com/forum/?fromgroups#!forum/ring-clojure). Of course, there's always the Clojure group on Google Groups (https://groups.google.com/forum/).
The Luminus template provides good starting defaults for a typical web application by using popular libraries. It also configures common tasks (such as logging) and provides a few default route handlers (URL handlers).
Taking a peek at the generated project.clj file, we see all the dependencies included by the luminus template. At the time of writing, the project.clj file produced the following dependencies:
Luminus is a popular and active project, and is constantly getting better. Between now and the time this book goes to press and you purchasing one for each of your friends and yourself, it's possible that the template will have changed. At the time of writing, version 1.16.7 of the luminus template was used. If you used a more recent version your results may vary.
The first dependency should look familiar (if not, then this book isn't for you… yet). The rest, however, might appear to be a mystery. I'll spare you the effort of searching it online and break it down for you.
The luminus template generates web applications using a fairly typical directory structure. However, it also produces a number of Clojure namespaces that can cause a bit of confusion if you're brand new to Clojure web development. You can either open the project using your favorite Clojure editor, or do the following from the terminal:
The preceding command line is a nasty thing to eyeball and type. You can copy and paste the preceding command from http://bit.ly/1F3TmdJ.
In either case, you should see output similar to the following:
Luminus generates three directories at the root of the application directory: resources, src, and test.
The resources directory contains the files that will compose the front end of our applications. The public folder contains resources publicly available to the client, such as our JavaScript, CSS, and images. By contrast, the templates directory contains our Selmer templates used for the heavy rendering of HTML parts. All of these files will be made available on our class path; however, only those in the public folder will be actually available to the client.
The src directory contains all of the necessary namespaces for running our application, and the test directory contains all the necessary namespaces for testing our src.
In addition to the directories, however, Luminus also generated some files in the src directory. These files are the bare minimum requirement to successfully run our application, and each one handles specific functionality. Let's take a brief look at the base functionality contained in each file.
The hipstr.util namespace is a simple namespace where you can put various helper functions you find yourself frequently using during the development of your application. Out of the box, Luminus generates a hipstr.util namespace with a single function, md->html, which converts markdown into HTML. Typically, I try to avoid namespaces such as util.clj because they eventually turn into the junk drawer in your kitchen, but they can be useful on smaller projects if things don't get too crowded. The following block of code shows the hipstr.util namespace: