A quick javascript tip that lets you eliminate small IF statements

Ok so it’s not really that kind of Short Circuit, though it is almost as cool. In javascript, as in many programming languages logical and statements short circuit if the first element isn't true. So basically if you say
if(false && true)
Javascript start processing the expression sees the false, knows that the statement can never be true and moves on without ever touching the true. This has some interesting practical applications. Because it means that you can use the first statement as an IF and the second can be your command to be executed.
Pull up your javascript console and try this:
( 1 === 1 ) && alert('Johnny 5 is alive!');
yep amazing! It does the same thing as:
if( 1===1) {
alert(' Johnny 5 is alive!');
}
Sure there are other short forms of that if statement that would work. But, the short circuited form is clever, and interesting. It really shows off one of the interesting aspects of the language that you don’t run into everyday. I think it’s kind of elegant. Not as readable, sure. Still a neat trick for creating slightly more compact code. I wish I could take credit for it, but I found it reading through someones pull request on git hub. When I find the project again I’ll post a link to it... Now it’s time for some hot chocolate and breakfast.
Let’s face it, ultimately the ideal solution for responsive images does not exists yet. Honestly, I am not sure that browser makers really have a dog in this fight so it will likely be a while before it gets done on their end. Hopefully the W3C will see all the discussion and decide to include something in the spec that would prompt browser makers to tackle this in a semantic way. Until then we are left with a variety of options that are not necessarily awesome.
Except this one, it's awesome. Ok, that might be a bit of hubris, the reality is this is just a more elegant hack. But before we dive into the details let’s discuss device detection, and why it is a short sighted solution, since it seems to be winning over hearts and allies.
Ultimately device detection has two major shortcomings: 1) security, and 2) it’s inability to determine display size. If you are writing your own server side device detection then there is really only one issue, #2, if you are using some one's third party service then you need to think long and hard about #1.
So security, whenever you rely on an outside service to manage any aspect of your site you are opening yourself up to the possibility that something will go wrong on their end and effect your site negatively. They could get hacked, they could go out of business, they could be purchased by someone with less than desirable intentions, or they could get knocked of the web by a DOS attack. I can hear you thinking: “But hey, they are only images. What’s the big deal?” Well there are a couple of big deals. First, javascript returned as the SRC of an image is executed in the browser meaning someone could execute arbitrary JS on your site. Setting that nightmare aside, if all the images on the third party system got replaced by ads to your biggest competitor, that would be a very bad thing for your website. As would all the images disappearing from your site because of an outage.
Of course these problems are purely theoretical, I have no idea what the security, plans or intentions of any of the sites providing this service are. But, they are possibilities that need to be considered.
Now for a more general issue with device detection and responsive images. Take a moment and read through all the comments on sencha.io src’s documentation. It becomes clear pretty fast that their are some drastic limitations to server side detection that are not shared by client side methods. The two big ones are: the inability to detect device rotation on mobile devices, and dealing with very large screens. Server side device detection requires you to setof default sizes for given devices. This means, in sencha.io’s case, that the maximum size of an image returned from automatic resizing is 980px. So if you need an image to display at 1300px on those beautiful new thunderbolt displays, and then automatically scale down to 120px on an iPhone, you are out of luck.
Sure you can specify the width of the image explicitly, but now you are back to doing browser size detection in javascript and rewriting the src of the image. Which you could have been doing all along without the outside dependency.
One of the realities of the responsive web is that it needs to scale up as well as down. Responsive design is about tailoring the experience to the particular users context, whether it is larger or smaller than your default. This means we shouldn’t be sending the same experience to someone on a 2000+px screen as we do to a 1200px screen. For me this is the last nail in the coffin for device detection as the ideal solution. It could be useful for setting smart defaults, but ultimately fails to provide a truly responsive experience.
Now on to the fun stuff, that probably brought you here in the first place: future friendly javascript-less client side responsive images. Be aware that these, much like using noscript, are still a little hack-ish. But, this seems to be a better solution than noscript to me.
The image tag, like pretty much every other element in html, can receive a background style. This means that we can create an image whose background changes, based on media queries. At this point I should insert the caveat that you need to use something like respond.js to make media queries work in Internet Explorer, but there are ways around that, depending on how you structure your media queries. Another drawback is that each image will need a unique identifier, probably an ID, so we can set its “source”. So now some example code:
<style> #myImage{
background:url(respond/img/myImage.jpg) no-repeat;
width:96px; height:95px;
}
<img id="myImage" src="respond/img.png" alt="This is a test" />
That’s really all there is to it. The respond/img.png is a 1px by 1px transparent png that weighs a whopping 96 bytes. It is the hack-ish part, but we need it to hide the alt text, and the missing image styles added in by the browser. Hopefully that need will go away in the future, and removing it would be very simple in that case.
This method opens up the door to some crazy stuff too. Like having different aspect ratios for images at different screen resolutions. Or like having all the images for a page stored in a single sprite per screen resolution. Imagine all your images coming in as essentially 2 http requests, one for the img.png and the other for all of them as a single image. Is that a good idea? I have no idea... but it is possible.
Hopefully someday soon we will have an img tag that is responsive from the get go, but for now we need to find the option that is going to work best for our particular environment and needs. This is my current favorite, though there are probably cleaner methods for doing this. I hope... if you know of one write it up so we can all discuss it more. Until then go forth and be responsive!
We’ve been talking about responsive design around the office a lot lately. It’s kind of a big deal these days. The holy grail seems to be responsive images, or a system that allows you to determine the correct size image for the users browser. This reduces the amount of data being downloaded by mobile devices while still providing a higher resolution version for desktop, and tablet browsers. By images I am talking about image tags, frameworks like 320 and up and media queries can take care of the layout images in css.
One of the best systems out there is by the Filament group, their code is also on GitHub. They are doing some awesome things that make it easy to get started with responsive images.
So in an effort to advance the discussion, and push this process even farther, here is a method for removing the double http request penalty associated with their system. Yep, you heard that right. 1 http request per image regardless of the size of your screen. And it’s cross browser compliant with a non-javascript fall back.
Let's take a quick look at the javascript:
var resizeImages = function(){
var imgs = $('img');
var width = $(window).width();
for(var i = 0; i < $(imgs).length; i++){
var thisImg = $(imgs)[i];
var thisSrv = $(thisImg).attr('src');
if(thisSrv == undefined || thisSrv == '')
thisSrv = $(thisImg).attr('data-src');
if(width > 1180)
$(thisImg).attr('src',thisSrv.replace(/\/[0-9]+\//,'/1180/'));
if(width > 960 && width < 1180)
$(thisImg).attr('src',thisSrv.replace(/\/[0-9]+\//,'/960/'));
if(width > 480 && width < 960)
$(thisImg).attr('src',thisSrv.replace(/\/[0-9]+\//,'/480/'));
if(width < 480)
$(thisImg).attr('src',thisSrv.replace(/\/[0-9]+\//,'/320/'));
if($(thisImg).hasClass('responsive'))
$(thisImg).removeClass('responsive');
}
};
Now that you have seen the bulk of the code we have a few things to talk about. First of all, the size cutoffs are totally arbitrary in this example. Second, this is a convention over configuration system. It requires that you have the responsive sized images stored in a strict directory structure and that you add a little bit of extra markup to handle the non-javscript fall back. But, we'll come back to that. Third, this uses jquery, though a library agnostic version would be a pretty simple derivative.
You can probably guess what the markup for an image looks like based on that function, either way here is what your markup would look like:
<img src="/respond/img/myImage.jpg" />
<img data-src="/respond/img/320/myImage.jpg" class="responsive" />
<noscript>
<img src="/respond/img/320/myImage.jpg" />
</noscript>
The first <img> tag is non-responsive. It will be ignored by the system and displays normally. The second, is what your <img> tags look like for a responsive image. No src attribute. This is important, it prevents the browser from hitting the server before we figure out what image size we need. The function above handles swapping the data-src into the src and replacing the 320 with the appropriate size directory. The responsive class is critical to this whole thing too. It should default to display:hidden so that the image doesn’t appear unless javascript is running. Also prevents a flash of missing image in IE.
The last image, the one in <noscript> tags is our fallback. If the browser does not support javascript the responsive <img>, which does not contain a valid src attrribute, will not load anything and remain hidden by the responsive class. <noscript> provides a last ditch fall back for our non-javascript users. One of the advantages to this is that it is only executed when needed, keeping http requests to a minumum. Another added bonus is you can specify what ever size image you want for the fall back. Yay freedom!
So <noscript> wrapped images are really what set this method apart. For every image you include in the page you will need to have a <noscript> wrapped version of the image immediately following, and styled similarly to, the responsive version. Is this the most elegant solution? Probably not. But for the price of a little extra code you eliminate duplicate downloads and unnecessary http requests.
One more major thing. Let’s talk about directory structure. Sorry... but it’s got to be discussed. Take a look at how the image directories are setup in the example code. There is an img directory with 4 subdirectories. Non-responsive images go in the base img directory. Appropriately sized images that will be served responsively go in each of the subdirectories. This means that you will need to provide 4 copies per image displayed on the page. Really though that’s a requirement of every responsive image solution out there.
Ok so really that wasn’t that bad was it? Here are the files and example directory structure. As always hit me up with questions or comments: Email me or tweet me.
Today on the 10 year anniversary of September 11th I thought I would reminisce about my memories from that day, far from New York City. I am working to compile my families’ stories and may expand beyond them to collect the stories of others who were far away from ground zero on that day. I pray that these stories and days will remind us that we are “One Nation Under God, Indivisible with liberty and justice for all”.
On the morning of September 11th, 2001 I was 17 and getting ready for a day full of work and school. I lived in southern Austin, TX with my parents and siblings and was attending Austin Community College, studying Computer Information Systems. I had two jobs, one working in the computer lab there, and the other at Randall’s, a grocery store owned by Safeway.
It started off like any other day, eating breakfast, getting ready for work. I had a class later in the day so I got my backpack loaded and ready to go.
I don’t know how we all wound up in the living room gathered around the TV, but we did. I stood off to the left of the TV watching in shock as the news stations stopped everything to cover the unfolding tragedy. I remember watching the first tower burning. I remember the confusion that seemed to grip the broadcasters as everyone tried to understand what was going on. I wasn’t an expert but that gash in the building looked too big for a small private plane...
And then we all found out it wasn’t. It wasn’t an accident, it wasn’t a small private plane. I caught sight of the second plane. I remember watching as the second plane slammed into the second tower and knowing this was an attack. My younger brother and I loved planes and knew immediately that a large passenger plane had been piloted into the towers. We recognized the tail paint.
For me the scope of the disaster was so broad that it didn’t seem quite real. I couldn’t quantify that kind of loss. I still wonder sometimes if I understand the true scope of what happened that day, the number of lives lost, the individual tragedies that played out. I am not sure if I ever really will, or if that is even humanly possible.
As the camera zoomed in on the burning, gaping hole in the first tower, I noticed something bright dripping from the corners and bottom. I knew it was molten metal, and prayed that they would be able to get everyone out before it came down. It could only be a matter of time before the structure failed. We as a family watched in a mix of silence, and speculative analysis.
The first tower came down just before I had to walk out the door to get to work. I was late for work that day, because I stayed. I had to watch. And then it happened. I watched in quiet horror as floor after floor was crushed by those above it as the second tower came down. I hoped beyond hope that everyone was out.
When I got to work the news was on at the grocery store. In the lulls between checking out customers' groceries we all wandered over to the TV they had setup to show the coverage. As the day progressed, those lulls got shorter and shorter and we got busier and busier. People were stocking up. There were rumors that Austin could be next and people wanted to hole up in their homes. Huge carts of groceries were flying up to our checkout lines and then out the doors. It was like the day before thanksgiving, except everyone had fear in their eyes.
I remember going out to a customer’s car and noticing the fighters, I remember them being pairs of F-15s, patrolling the skies. Not a normal sight in Austin since the closing of Bergstrom Air Force Base. I am not sure if it was more comforting or nerve wracking to see them there, but there they were flying patterns over the Capitol of Texas.
I was a little nervous about going to school later in the day. The campus of Austin Community College I was attending was one of the highest towers in the area back then. But tactically it wasn’t much of a target. I thought they would close it, hoped they would close it, but they didn’t so I left work and drove to school.
I watched the sky my entire drive there.
Almost no one showed up for class. Our professor had been in the air force and so we talked about what was going on for most of class. I think there were two other students in the classroom. After that is back home, and I don’t remember much of the rest of that day.
In the days that followed came numerous discussions with my mother about what this meant. What war would mean, because it was clearly coming. Most of our talk was about the draft, seemed like everyone thought that it was going to be re-instituted in those early days after 9/11. I remember that Mom mentioned being a conscientious objector to me. I told her I couldn’t. If my country was under attack, and needed me to serve, I would do it willingly. Because it’s what my church had always taught me, and what I believed in. That freedom is worth dying for. I still believe that and am proud to be part of country filled with others who believe the same way, and put there lives on the line for it day after day.
This morning after reviewing the hackmycf.com* scan results for ansble.com I noticed that the only major security issue that turned up was that the railo admin was accessible from a public IP address. “Hmm...” I thought, “I wonder how you lock that down properly, using the reverse proxy setup I am running.” I figured I could do it in tomcat, but that would get ugly fast if when I start scaling out my application servers. So after some googling I found several other posts on securing the railo admin.
Particularrly after reading Marcos Placona’s post on doing this in Apache, I figured that something similar could be done in Cherokee. Turns out it can and here is how you do it:
cherokee-admin -b).http://yoursite.com:9090.
That’s all there is to it. Your admin panels have now been hidden for all your railo servers, and any you might add in the future. You are on your way to a more secure server setup. Good luck out there!
* If you aren't checking your servers with hackmycf.com, why not? You should be. It's an awesome service and has a free option. Go try it out.
Over the last week and a half I have been working on a bare-bones internal reporting tool for the organization I work for. If you want to take a look at the interface... It’s coming along nicely and has been a the fun kind of project that let's you try new things, like writing a custom RTE.
One of the issues that I have had to deal with is the document export system. ColdFusion’s cfdocument tag makes it very easy to create a PDF, at a cost. The cost is that cfdocument really only has rudimentary support for CSS, and as a result, styling the contents of that PDF is a mess. So the specific issue I had was with styling sub-lists to have a different bullet then their parents. Makes sense, that’s what most word processors do. In CSS this would be really easy:
ul, ul ul ul ul{list-style:disc}
ul ul, ul ul ul ul ul{list-style:circle}
ul ul ul, ul ul ul ul ul ul{list-style:square}
As beautiful and simple as that is, it totally falls apart in cfdocument. All the lists are displayed with disc style regardless of how you style them. After some experimentation I realized that in order to get the same effect in cfdocument you have to add type=”circle”, or type=”square”, to the individual li tags. You read that right, not the uls the lis.
I tinkered with using RegEx, both the JAVA and ColdFusion implementations, using lookaheads and lookbehinds, to try and wrestle the PDF file into submission. Mostly though I wound up getting wrestled into submission... until I had a logical breakthrough.
HTML documents are XML. With that in mind I tackled the problem from that angle and wound up with this code:
reportString = xmlParse(reportString);
secondLevel = xmlSearch(reportString,"//body/ul/li/ul/li");
for(i=1; i lte arrayLen(secondLevel); i++){
secondLevel[i].xmlAttributes.type = 'circle';
}
thirdLevel = xmlSearch(reportString,"//body/ul/li/ul/ul/li");
for(i=1; i lte arrayLen(thirdLevel); i++){
thirdLevel[i].xmlAttributes.type = 'square';
}
fourthLevel = xmlSearch(reportString,"//body/ul/li/ul/ul/ul/li");
for(i=1; i lte arrayLen(fourthLevel); i++){
fourthLevel[i].xmlAttributes.type = 'disc';
}
reportString = toString(reportString);
So a quick discussion of what is going on here and we’ll call it good. Since we are starting with a string that contains the generated report we need to parse it into an XML variable. xmlParse() makes that very easy. From there it’s all xmlSearch() and XPath queries to isolate the elements we want to add the type attribute to, looping over them and then converting the XML variable back to a string.
One interesting note: the arrays returned by xmlSearch are passed by reference, so the changes you make to them are reflected in the original XML variable.
That gets us to four lists deep, and could be expanded further if necessary. Amazingly the CSS covers six. In three lines! Hopefully the CSS support in cfdocument will improve over time, but until then when you need to style sub-lists this seems to be the way to go. Good luck out there!
I am working on a little side project (ansble.com) which is going to require scalability, and a layered architecture that I just couldn't reasonably build in a physical environment. So I started toying with Amazon Web Services and realized that there wasn’t a lot of documentation on the server combination I was planning to use.
The whole architecture is fronted by Cherokee web server, a really fast web server that puts apache and even nginx to shame. It also has a beautiful admin site that makes configuration a breeze. Behind that the app server layer is Railo running on Apache Tomcat. Railo is fast, free, and fast. The DB layer is CouchDB, with a second Cherokee server handling load balancing between the Railo layer and the CouchDB layer. The other decision was to use the Amazon Linux AMI in order to take advantage of Amazon’s hard work and updates.
To get started let’s spin up four Amazon Linux AMI instances (go 64 bit, all the software we are dealing with supports it so no reason for 32 bit). Put all of them in the default security group and then create a security group for each layer of the architecture (One for web servers, application servers, load balancers, and database servers) and place one instance in each group. The instance that will be your web server instance should be in the default security group and the web servers security group. This is important because you can’t change security groups after you spin up your instances.
That done, let’s setup the Railo server first so we can configure the web server as soon as we install it. SSH into your app server instance (something like ssh -i mykeyIcreated ec2-user@myec2instance.amazon.com on linux, or os x) and follow these steps:
sudo yum upgrade to upgrade and update the server instance. When I wrote this there were about 121 MB worth of updates as soon as I spun up the instance.mkdir railoInstaller)cd ~/railoInstaller and then wget http://www.getrailo.org/down.cfm?item=/railo/remote/download/3.2.3.000/tomcat/linux/railo-3.2.3.000-pl0-linux-x64-installer.run to download the installer.chmod 744 railo-3.2.3.000-pl0-linux-x64-installer.run)sudo ./railo-3.2.3.000-pl0-linux-x64-installer.run). Make sure you create a user for railo and tomcat when it asks what user to run it under.cd ..) and delete the railoInstall folder (rm -r railoInstall)
That’s all there is to getting a basic Railo server up and running on AWS. You will still need to put files on it and setup the contexts but this gets the box up and running and brings us to... the Cherokee web server! SSH into your web server instance and follow these steps:
sudo rpm -Uhv http://apt.sw.be/redhat/el5/en/i386/rpmforge/RPMS/rpmforge-release-0.3.6-1.el5.rf.i386.rpmsudo rpm -Uvh http://download.fedora.redhat.com/pub/epel/5/i386/epel-release-5-4.noarch.rpmsudo rpm -Uvh http://dl.iuscommunity.org/pub/ius/stable/Redhat/5/i386/ius-release-1.0-8.ius.el5.noarch.rpmsudo yum upgrade to upgrade and update the server instance.sudo yum install cherokeesudo cherokee-admin -bctrl+c -ing it. Done with Cherokee!
Now that we have an App Server Layer and a Web Server layer we can turn our attention to the DB Layer and the load balancer for it.
We’ll start with CouchDB since we already know how to setup Cherokee. This is the most complicated install of the three servers but it’s not that bad really.
sudo rpm -Uhv http://apt.sw.be/redhat/el5/en/i386/rpmforge/RPMS/rpmforge-release-0.3.6-1.el5.rf.i386.rpmsudo rpm -Uvh http://download.fedora.redhat.com/pub/epel/5/i386/epel-release-5-4.noarch.rpmsudo rpm -Uvh http://dl.iuscommunity.org/pub/ius/stable/Redhat/5/i386/ius-release-1.0-6.ius.el5.noarch.rpmsudo yum upgradesudo yum install gcc gcc-c++ libtool zlib-devel openssl-devel rubygem-rake make gitgit clone https://github.com/iriscouch/build-couchdb.gitcd into build-couchdbgit submodule initgit submodule updaterakebuild-couchdb/build/etc/couchdb/local.ini)couchdb couchdb-build/build/bin/couchdb -b and you’re done with CouchDB setup.
That brings us to the last server. The Cherokee load balancer that will sit in front of our CouchDB layer. It’s the same exact process we used for Cherokee before but I’ll repeat it so you don’t have to scroll back up there to read it.
sudo rpm -Uhv http://apt.sw.be/redhat/el5/en/i386/rpmforge/RPMS/rpmforge-release-0.3.6-1.el5.rf.i386.rpmsudo rpm -Uvh http://download.fedora.redhat.com/pub/epel/5/i386/epel-release-5-4.noarch.rpmsudo rpm -Uvh http://dl.iuscommunity.org/pub/ius/stable/Redhat/5/i386/ius-release-1.0-6.ius.el5.noarch.rpmsudo yum upgrade to upgrade and update the server instance.sudo yum install cherokeesudo cherokee-admin -bdecimalWith that done you now have a very flexible architecture that will allow you to scale out any layer that presents performance issues. My tests with blitz.io show that this basic setup should be able to handle as up to 12.5 million requests per day with no performance enhancements to the servers. It’s fast. As always if you have questions, thoughts, criticism shoot me an email or @ reply me on twitter. Good luck out there!
PS: if you sign up for blitz.io and use this link I'll get some additional concurrency to test things even better!
My wife, Nancy, is writing 100 songs in 100 days. Yes you heard that right, 100 songs in 100 days, and no, not just a new riff, but a new song. Even for the most gifted song writer, and I think that's probably her, this would be a Herculean task, requiring perseverance and patience. And now 62 days in that is exactly what she has done.

Nancy has always loved to write and has an uncanny ability with words. It has been really amazing to watch as she has cranked out lyrics, fiddled with chord progressions, and recruited talented people to sing with her for videos. It has been an enormous task!
It really has been an incredible project to witness, so go check out her blog: 100 Songs 100 Days and help cheer her on to the finish. Help us get the word out about this project!
I realized tonight that I have a whole bunch of projects lying around that aren't mentioned anywhere here on designfrontier. So to remedy that I decided to put together this quick article.
RandPop : a responsive website for creating random numbers in a variety of forms, from flipping a coin to sets of random numbers. More features are in the works though this particular project is on hold at the moment. The dice (which are completely created with CSS3 gradients) came in handy the other day playing with my nieces and nephews).
TypeSette : Back when I was putting together The Adventures of Sherlock Holmes I needed a quick and easy way to clean out the extra line breaks, and whitespace in Project Gutenberg versions of the text. So I created typesette to automate that process.
Random LDS Talk : Every once in a while I want to read a random religious article so I wrote a quick ColdFusion app that parses the RSS feeds on LDS.org and redirects you to a random selection. Most interesting part was writing the Java based web scraper for the General Conference Archive, since it didn't already have a feed. Still a little buggy but works good enough for now.
Stand Resolved : A simple goal tracking application designed to give you a daily reminder of what your goals are. Mostly defunct at this point. If you are interested in purchasing the domain let me know... I may redesign and develop it as a mobile app in the future.
I recently wrote about it but I might as well mention it again. Tokenizer is my first open source project, a form token management system designed to make fighting XSRF as simple as possible.
Well that's the run down of the smaller personal apps I have out there. Check them out and let me know if you have any suggestions for where they can be improved. Email or twitter is the best way to get ahold of me
I promised Richard Davies an article about the use, and purpose behind Tokenizer the token (if you think of them as nonces and not tokens just substitute nonce everywhere I say token...) management project I released a few weeks ago. Since then it has been picked up by OWASP’s ColdFusion resources page and viewed over 900 times. So this may actually be a little late...
Rather than me going into an in depth exploration of XSRF (or CSRF - cross site request forgery) you should go read Jeff Atwood’s fantastic article he explains it much better than I could (seriously, go read that article). In brief XSRF is firing a POST or GET request invisible to the user of the website for malicious purposes. Now that you have read the article let’s get down to brass tacks.
There are three ways to protect against XSRF. One, check to make sure the request is originating on your server (Portcullis and other application firewalls often do this). Two, add a unique token (aka hidden-input-field-with-a-value-matching-one-stored-in-the-session-scope) to the form. Three, double submit your cookies. Tokenizer does the second, the others are up to you and other libraries to implement.
Tokenizer’s purpose is to take the heavy lifting out of creating, checking, and expiring the tokens in your forms, and all your forms should have tokens. The basic life-cycle of this approach is: 1) create a token and store it in the session scope 2) write the token’s value to a hidden form input 3) when the form is submitted check to make sure the value in the form variable matches the value in the session, and that it has not expired 4) remove the token from the session scope once form processing is complete.
So let’s walk through how that is implemented in Tokenizer. Before we do anything else we need to make sure that we have an instantiated Tokenizer to use. Pass it the session scope so that knows where to store the tokens.
tokenizer = createObject('component','com.tokenizer').init(session);
Step 1
To create the token we pass the createToken() method a unique name, and a timeout (in milliseconds). The createToken() method creates a token within the session.tokenstore struct with two variables in it, the token and the expiration.
tokenizer.createToken('selfPostTest',300);
and here is what it looks like when you dump out the session:

The second step in the life-cycle is writing the token to the page, which we do with the writeTokenToPage() method. Passing it the name of the token we just created like this:
#writeOutput(tokenizer.writeTokenToPage('selfPostTest'))#
This creates a hidden form input that contains the token and writes it out to the browser.
Step 3
With that done we need to add the code to check for the form submission. This goes right below the init() call for Tokenizer, either on the page housing your form (if self posting) or on the page doing the form processing (in which case you need to initialize tokenizer on both pages). This is a stripped down IF statement, but it contains the two elements that you need to check for with tokenizer. First check to ensure that the token exists in the form, second pass the name of the token, and the value from the form to the checkToken() method.
if(structKeyExists(form,'xsrf_token') and tokenizer.checkToken('selfPostTest',form.xsrf_token)){
//processing code goes here
}
checkToken() verifies that the token exists, that the session and form values match, and that the token has not expired.
Step 4
Inside that IF statement, somewhere near the bottom we need to get rid of the token so it can’t be reused. This prevents the token from being used for more than one form submission.
tokenizer.removeToken('selfPostTest');
And that is really all there is to it. The goal was to make this as simple as possible, so if you think of ways this could be better please let me know (daniel@designfrontier.net or @daniel_sellers). If you want to see how this all fits together you can grab a copy of tokenizer which includes both self-posting and non-self-posting examples. Good luck out there!