The Middleman build environment
Rails has long had the concept of environments built-in. That is, the ability to set the environment to development, production or test, and only run code when in one or more of those environments. For example, the development environment has class caching turned off by default, so that code is reloaded on every request, perfect whilst developing. In production, this is turned on, for much improved performance.
Middleman has a similar idea, but the environments are build and development.
I recently took advantage of this feature, specifically, the build environment.
The build environment is set when the site is being built using middleman
build
. I used this to only include Google Analytics tracking code when the
site is built. This stops local web browsing from affecting my web statistics.
In my layout.erb
, I've used the build?
helper to conditionally include the
relevant JavaScript code.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<% if build? %>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'xxxxxxxxxx']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
<% end %>
As you can see, this is very simple, but also very useful for customising templates at build time.