<?xml version="1.0" encoding="UTF-8"?><feed xml:lang="en" xml:base="http://" xmlns="http://www.w3.org/2005/Atom"><title>Jason Earl Dot Com</title><updated>2008-10-23T03:47:49Z</updated><link href="http:///blog/atom_feed.xml"/><entry><updated>2008-10-23T03:31:48Z</updated><title>Fixing jQuery and Java Applets</title><id>http:///blog/fixing_jquery_and_java_applets</id><content type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml"><p>I&#8217;ve been pretty quiet recently. Not a lot has happened except I&#8217;ve been working a fair bit recently, along with trying to pull myself out of various bits of mess I landed myself back at the end of spring. Today I&#8217;ve run into a nasty bug with jQuery and Java Applets.</p>
<h2>The Bug</h2>
<p>Due to the nature of jQuery it appears that it likes to transverse through the <span class="caps">DOM</span> and do various alterations to it. This is all fine, until it comes to a pesky Java Applet. Java Applets however modify the behaviour of the host <span class="caps">EMBED</span>/<span class="caps">OBJECT</span> tag, probably because the Applet&#8217;s public methods are exposed as an external interface so that the applet can be controlled by JavaScript.</p>
<p>currently there is a bug open for this on the <a href="http://dev.jquery.com/ticket/2349">dev site</a></p>
<h2>The Fix</h2>
<p>My way round this was to block jQuery from attempting to attach events to the JavaApplet. The implementation is a little dirty (see link above about issues with <span class="caps">OBJECT</span> being used in <span class="caps">XHTML</span> 2.x to replace <span class="caps">IMG</span> tags).</p>
<h4>Place this below &#8216;nodeName&#8217; function</h4>
<code class="ruby"> 
<![CDATA[
	isExternal: function(elem) {
		return (jQuery.nodeName(elem, 'embed') || jQuery.nodeName(elem, 'object') || jQuery.nodeName(elem, 'applet'));
	},
	isHtmlElement: function(elem) {
		return !(elem.nodeType == 3 || elem.nodeType == 8 || jQuery.isExternal(elem));
	},
]]>
</code><h4>Replace &#8230;</h4>
<pre><code>@elem.nodeType == 3 || elem.nodeType == 8</code></pre>
<p>&#8230; with &#8230;</p>
<pre><code>!jQuery.isHtmlElement(elem)</code></pre>
<p>&#8230; throughout the rest of the jquery.js file.</p>
<p>Hopefully this will save a few other people going through the torture I had to go through, particularly as Internet Explorer also throw up some rather vague errors in the process of testing.</p></div></content></entry><entry><updated>2008-08-27T12:05:22Z</updated><title>Fixing Rails Scripts </title><id>http:///blog/fixing_rails_scripts</id><content type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml"><h2>Windows Line Endings Considered Harmful</h2>
<p>While I prefer and tend to use Ubuntu for most of my work, I occasionally have to do bits in OS X and Windows. Windows is a nightmare of an operating system at the best of times, but what often get caught out by is the fact that Windows line endings are CR LF based, which really upsets shell scripts in Linux/Unix. Whats more is that the errors you tend to get are not very descriptive, whether it be a script run from the console, or through web gateway interface (i.e. public/dispatch.*).</p>
<h2>Executable Permission Bit</h2>
<p>Another thing I often find that gets lost in translation is the executable permission bit if things get archived, or put on <span class="caps">FAT</span>/<span class="caps">NTFS</span> drives (i.e. flash <span class="caps">USB</span> disks). Subversion has an explicit svn:executable property, however git will just inherit the permission from the underlying operating system. Both have systems have advantages and disadvantages to their approach.</p>
<h2>The Rake Task</h2>
<p>In case you need to reset these for some odd reason here is a rake task I hacked up that deals with this. You will want to make sure you have dos2unix installed. Normally it is in a package called <code>tofrodos</code> in Debian systems, and can be installed with <code>sudo apt-get install tofordos</code></p>
<h4>Add to lib/tasks/fix_scripts.rake</h4>
<code class="ruby">
<![CDATA[
namespace :install do
  desc "Fixes any issues created from Windows new line termination and sets scripts as executable"
  task :fix_scripts do
    unless `which chmod`.empty?
      # Having executable on anything that shouldn't is annoying as some GUI's run the script instead of open it
      `find . -type f -print0 | xargs -0 chmod -x`
      # These need to be executable
      `chmod -R +x ./script`
      `chmod -R +x ./public/dispatch*.*`
    else
      STDERR << "WARNING: chmod command not installed. You probably are not running a *nix"
    end
    # Remove any DOS line endings coz they screw up shebang lines
    unless `which dos2unix`.empty?
      for file in Dir['./script/**/*'] + Dir['./public/dispatch*.*']
        `dos2unix -d #{file}` unless File.directory? file
      end
    else
      STDERR << "WARNING: dos2unix command not installed. No attempt to resolve line ends has been made"
    end
  end
end
]]>
</code></div></content></entry><entry><updated>2008-08-22T19:33:23Z</updated><title>Overlooked Rails Best Practises Pt.3</title><id>http:///blog/overlooked_rails_best_practises_pt_3</id><content type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml"><p>In this post I want to cover a number of very Rails specific ways to make code more robust. Many of these are small defensive coding techniques, but some also help tie down security issues.</p>
<h2>Use of Active Record Bang Methods</h2>
<p>Bang methods are methods that end with an exclamation mark. Their root is from impure functional languages such as <span class="caps">LISP</span> where this was used to denote side effects (mutability, IO etc). In ActiveRecord this is used to force exceptions to be raised if an action fails to act on the database due to validations, or failing callbacks.</p>
<code class="ruby">
<![CDATA[
ModelName.create!
some_record.save!
some_other_record.update_attributes!
]]>
</code><p>I always had a tendency to avoid using these methods initially when I started off programming in Rails. Probably because I have a bit of a hatred for exceptions. This probably stems from the annoyance they cause when I was forced to do some university work in Java (I hate the fact you have to bloat up trivial code with catch clauses, and putting throws in method prototypes). Likewise in C++ exceptions are considered a bit of an evil because they don&#8217;t play nicely with raw pointers.</p>
<p>However in recent Rails projects I found that the except based Active Record methods can be a great aid during development. One area particular is during migrations. During development I have a tendency to break migrations into the following three main initial files:</p>
<ul>
	<li>Schema Creation</li>
	<li>Data Loading</li>
	<li>Development Data Loading</li>
</ul>
<p>During the data loading, I find it handy to use code to create basic model instances, such as initial users etc. By forcing exceptions you can be assured that all of the actions you execute will happen and there will be no cases where data will silently fail to save back to the database.</p>
<p>Another case where these methods become useful is during transactions, as exceptions will force transactions to rollback. It is often a good idea to use transactions in databases to ensure actions are atomic, not to mention in some databases the use of transactions can aid the speed up operations by reducing the communication between the DB server and client libraries.</p>
<h2>Use of Closures or Symbols for Meta-Programming</h2>
<p>Due to the event driven model of Rails programming, there are many methods such as <code>before_filter</code>, <code>after_filter</code>, <code>before_save</code>, <code>after_validation</code>, etc that can be defined either by overriding the function, referencing a function through a symbol, or passing a block code.</p>
<p>Unless there is a critical requirement for speed (in which case you are probably using the wrong language) then one should always use symbols or &#8216;proc&#8217; objects. The issue when you override methods can make it very easy if you are using inheritance to block calls to callbacks defined in the parent class. This can be an issue when developing projects in teams as it means other developers will need to check parent classes when ever they want to use a filter.</p>
<h2>Use of &#8216;attr_protected&#8217;</h2>
<p>I would guess most people are educated enough to know about <span class="caps">SQL</span> injection security issues. However it is very easy to overlook sensitive fields like password hashes, salts, and other credential-orientated. Without attr_protected it is very easy to exploit mass assignment in Rails for one who knows or has a good idea how the database schema works.</p>
<h2>Indexes on Tables</h2>
<p>Again, this is a common mistake, and I often make this mistake. While pre-mature optimisation is considered to be an evil in programming, indexes are a very passive / non-intrusive form of optimisation. Typically one should look at placing indexes on any fields that are heavily used in comparison criteria. While ad-hoc guesses at optimisation can be bad, this will generally avoid your site from suddenly crawling in production mode due to drive seeks and heavy memory usage.</p>
<h3>Understand Your Database</h3>
<p>Clearly ad-hoc optimisation should not be substitute to a proper database tune, but it will quite often your intuition will be helpful. Likewise one should take time to clearly understand how your database uses indexes.</p>
<h3>Common MySQL Example</h3>
<p>MySQL and PostgreSQL have very different techniques and features. For instance MyISAM tables have great text indexing support, but lack any form of atomic safety for transactions. Clever DBA&#8217;s have exploited this by using InnoDB for most data, and have used replication to mirror text-search content to a slave database that uses MyISAM to provide fast text searches.</p>
<h3><span class="caps">GIS</span> and Spatial Data</h3>
<p>MySQL has some very basic spatial data type support. PostgreSQL has even better support. Spatial data such as locations can not use your typical linear B+ tree based index, because the data works in several dimensions. Typically most DB systems will use bounding box based systems using structures such as R-Trees. While it&#8217;s not important knowing exactly how these algorithms use, a good programmer / <span class="caps">DBA</span> needs to be aware how to make the best use of them.</p>
<h2>Avoid Using Direct <span class="caps">SQL</span></h2>
<p>Active Record is a very powerful abstraction for <span class="caps">SQL</span>. You rarely need to use <span class="caps">SQL</span> directly if you use it properly. However, I still see a number of Rails projects with significant chunks of <span class="caps">SQL</span> code.</p>
<h3>Complex Queries</h3>
<p>Even in cases where queries can get potentially very complex, such as search systems with large permutations of criteria, the use of scopes, and/or external libraries such as ThoughtBot&#8217;s Squirrel can still allow you to avoid this.</p>
<h3>DB Specific Features</h3>
<p>In cases where you do find you need to use direct <span class="caps">SQL</span>, it should generally only be when you need to exploit DB specific features or speed. In the case of speed, one should look at alternative indexing strategies first. Failing that, I have found it helps to hide each vendor&#8217;s <span class="caps">SQL</span> specific code behind modules that can be included to Active Record on the fly on start up. This way all vendor specific code it clearly isolated.</p>
<h3>Don&#8217;t Develop With MySQL</h3>
<p>Surely you would have seen the rant on MySQL I made. MySQL is like VB for databases. It encourages some really poor practices. If you use PostgreSQL for development and SQLite (where possible) during development, you can pretty much guarantee it your code will work on MySQL in production (and you can always run tests using MySQL occasionally to ensure this is the case). Many apps coded with MySQL often have silly syntax issues when switching to another database system. To be honest, in most cases PostgreSQL and SQLite are far superior alternatives for a fair amount of projects.</p>
<h2>Conclusion</h2>
<p>I think this wraps up some fairly trivial, yet handy ways to write more robust Rails code. It always helps to keep an eye on blogs such as &#8220;The Rails Way&#8221; and the &#8220;Ryan Baits&#8221; blogs. &#8220;The Rails Way&#8221; promotes a number of ways to improve code using existing projects as examples. Ryan Baits will keep you updated with all the progress in edge Rails which often contains improvements to help <span class="caps">DRY</span> up code.</p></div></content></entry><entry><updated>2008-08-16T03:26:40Z</updated><title>Sucks To You: MySQL</title><id>http:///blog/sucks_to_you_mysql</id><content type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml"><p>Excuse the AvenueQ reference here, basically horrible as it sounds, this is going to be one of my programming rants. I have a couple of pet programming rants I tend to find myself repeating, this is one of them and in due course I may even put the other rants up here. That way I can just point people to this blog instead of repeat myself yet again.</p>
<p>MySQL is one of the many popular Open Source systems that I hate because it gets way too much credit than it really deserves, not to mention the biased option that people tend to have. On top of this, much like <span class="caps">PHP</span> (yet another rant, for another day!), MySQL seems to have a somewhat deluded and brainwashed user base. While this post will come across as somewhat grumpy and scathing towards MySQL, the main reason I wanted to write this was to clear some of the common myths / misconceptions about MySQL that seem to have spread round the internet like some virus to developers.</p>
<p>All in all, I will bold enough to say that MySQL is as evil to <span class="caps">SQL</span> as VB is to programming in general.</p>
<h2>Encourages Non-<span class="caps">ANSI</span> Standards</h2>
<p>Firstly, the first thing that annoys me no end about MySQL is while it is generally compatible with <span class="caps">ANSI</span> <span class="caps">SQL</span> 92 standards, it seems to encourage users to write poor <span class="caps">SQL</span> code that is not portable. It would not be a surprise to me if this was some cunning design plan my MySQL&#8217;s management as a poor means to building some form of vendor locking through developer ignorance.</p>
<p>For example, the MySQL often encourages developers to use non standard characters such as backticks instead of double quotes for specifying structure names such as field and table names. The other common trick is to use C style string escaping that uses the backslash instead of the using two double quotes like the <span class="caps">ANSI</span> <span class="caps">SQL</span> standards specify. Unless you manually tell MySQL to use <span class="caps">ANSI</span> compatible <span class="caps">SQL</span>, it will generate it&#8217;s quirky <span class="caps">SQL</span> commands when creating dumps, which I guess has encouraged many developers who started databases with MySQL to follow this ill-fated convention.</p>
<p>As a result, there are so many Open Source projects where you run into issues if you want to use SQLite or PostgreSQL because the <span class="caps">SQL</span> code they give you for basic <acronym title="Data Manipulation Language"><span class="caps">DML</span></acronym> statements uses the MySQL specific quirks.</p>
<h2>Bullcrap Marketing</h2>
<p>MySQL only dominates the Open Source DB market because it&#8217;s had corporate marketing, which has lead people to believe absolute crap. The reality is that it&#8217;s a known fact that PostgreSQL is a far more stable and feature rich <span class="caps">RDBMS</span>, and has been for many years compared to MySQL. Yet if you enter put &#8216;MySQL vs PostgreSQL&#8217; into Google, you&#8217;ll be inundated with shoddy reviews which all claim that MySQL is X number of times faster for practically everything.</p>
<h3>MySQL <strong>Can</strong> Be Damn Slow!</h3>
<p>From experience, having run into major performance issues with MySQL before, I looked at PostgreSQL. I found the issue with MySQL was that it would only use one index per a table / aliased table, which was making it slow. There was no way to get round this in a graceful manner using MySQL, and due to the requirements of the application I was coding, I couldn&#8217;t really adapt it to work round this rather undocumented design flaw of MySQL. Basically, what I needed was MySQL to be able to utilise several indexes per a table because the nature of the query was one where any number of field criteria where being applied in a flexible way. For instance, sometimes I needed just to search by a given location, sometimes it was for a given price range, sometimes it for was for entries modified in a given date range, but on top that any permutation of those criteria could be combined. For instance someone might want to search by location, price range and date range. However MySQL was too dumb to be able to use each of the indexes separately, combine the results using set logic and then get rows based on the result of the set operations. As a result, MySQL was <strong><span class="caps">SLOW</span> AS <span class="caps">TURD</span></strong>.</p>
<p>PostgreSQL did not have this annoying restriction and thus was much faster. The bottom line is that MySQL is fast for very trivial queries, however for more complex applications you can soon run into serious issues due to it&#8217;s design flaws. This annoys the hell out of me because people are dumb enough to assume the trivial benchmark results for simple queries still hold up for their application in the real world, despite the context being completely different. I only came to realise that the indexing system in MySQL was my problem because I quickly picked up how the query optimiser was utilising indexes in both MySQL and PostgreSQL from commands such as <span class="caps">EXPLAIN</span> <span class="caps">SELECT</span>. Thankfully, I was able to see past the brainwashing that existed on many comparison benchmark pages.</p>
<h2>Quirky As Hell &amp; Lacking In Features</h2>
<p>OK this is not such an issue as MySQL has been playing catch up as both versions 4, and 5 have managed to start implementing things like transactions, joins, etc. However back in the day of MySQL 3.x, it was pure hell trying to do anything a real database was supposed to do. MySQL was really nothing more than a fancy file storage interface. Even so, MySQL is still playing catch up heavily to PostgreSQL in terms of typical database features that a quality database system should be capable of doing. <span class="caps">GIS</span> support is just one area where I realised this.</p>
<h2>Licensing</h2>
<p>This isn&#8217;t a major issue and many other places mention it, but people often forget that MySQL is not as free as it sometimes appears to be. It licensing is far muddier than the plain and simple <span class="caps">BSD</span> license that PostgreSQL offers.</p>
<h2>Conclusion</h2>
<p>While this doesn&#8217;t seem the most productive of blog posts, my main point was to highlight how MySQL has got developers into bad habits, and clear up the generally deluded reviews of MySQL that exist all over the internet, rather than sound like a grumpy old sod. If you are still using MySQL, seriously look at PostgreSQL or SQLite as alternatives. While developers are responsible for researching what <span class="caps">RDBMS</span> is suitable for their projects, I have to say from personal experience PostgreSQL generally tends to be far better system for larger projects than MySQL. For small projects where you don&#8217;t need to scale up in a distributed manner SQLite is great because it&#8217;s lightweight and hassle free. As a rule of thumb I try hard to ensure my <span class="caps">SQL</span> code is portable and that I minimise using vendor specific elements in order to keep my options open. When I do need to fall back on vendor specific code, I try hard to ensure it&#8217;s clearly documented and abstracted away.</p></div></content></entry><entry><updated>2008-08-16T02:13:06Z</updated><title>Overlooked Rails Best Practises Pt.2</title><id>http:///blog/overlooked_rails_best_practises_pt_2</id><content type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml"><p>In my previous post I covered in bit of depth some of the issues relating to the Rails fixtures system. In this post I&#8217;ll cover a couple more bad coding smells that make me cringe, along with simple defensive fixes that will hopefully protect you (especially for those who are still novice Ruby/Rails programmers) from hidden bugs arising later in your development cycle.</p>
<p>In this post I will probably follow on where I left off with issues relating to the issues caused by global data. I am going to home in on a couple of very simple gotchas that I don&#8217;t often see mentioned very often in the Rails &#8216;blogsphere&#8217; that can lead to some very hard to trace bugs that only show up much later in the development cycle (or in some cases not until production deployment).</p>
<h2>Use Class / Module Variables With Caution</h2>
<p>Code such as:</p>
<code class="ruby">
<![CDATA[
class User
  cattr_accessor :some_variable
  self.some_variable = 'Some String'
end
]]>
</code><p>This was a major gotcha for me when I started using Rails. Many Rails programmers will use class and module variables without giving much thought. Because the variables exist within the scope of the related module or class it is easy overlook the fact this data is effect global.</p>
<p>What&#8217;s more is that issues created from this sort of code virtually never manifest themselves in development. The Rails development environment large chunks of code on request, and further more generally runs as a single web server instance.</p>
<h3>Why is this an issue?</h3>
<p>Firstly, the biggest problem relates to what I outlined above, is due to the way the development environment shielding you away from the side effects this will cause. As a result you will end up with bugs in production that magically disappear when you try and debug them when go into development mode. This is a classic example of a <a href="http://en.wikipedia.org/wiki/Unusual_software_bug#Heisenbugs">&#8216;Heisenbug&#8217;</a> in the making!</p>
<h4>Example Scenario</h4>
<p>A typically example where this will manifest is when you have multiple Rails&#8217; instances running, each request is for a given user can be sent to any of the Rails instances running. However each Rails instance is not going to have it&#8217;s own class and module level variables. That is if Joe is served by instance A, which sets a class level variable during the request. When Joe makes another request, it might end up being sent to instance B, because instance A is busy. However because each instance has it&#8217;s own class level variables, it can not expect the variable it set in instance A to exist in instance B. That is Rail&#8217;s should really be treated as a <a href="http://en.wikipedia.org/wiki/Shared_nothing_architecture">shared nothing architecture</a>.</p>
<h3>Further Issues.</h3>
<p>In many cases Rails sites often utilise the ability for user&#8217;s to login. A common pitfall here is that user-sensitive data is held in any sort of class level variable, you are going to run the risk of leaking user data between different users. This is not nice given the fact that this issue probably will not expose its self even if you are using some sort of functional tests within your project.</p>
<p>Another overlooked issue is the the possibility for memory to &#8216;leak&#8217;. Well, the memory doesn&#8217;t as such leak, but any variables referenced from a class level variable will not get picked up by the garbage collector. This applies to all variable data with it&#8217;s referenced directly, or indirectly through a chain of several variables. If you have to store data in class or module variables, it&#8217;s generally best to try and stick to simple data types, such as strings and numbers. It is always good when deploying an application to use something like <a href="http://www.tildeslash.com/monit">monit</a> to keep a watch on memory consumption, not just on Rails app, but also any part of the Rails application that might run in a persistent / daemonised manner (such as a rake task that remains running in the background until explicitly terminated). I have been caught out a couple of times by unchecked memory consumption myself (Mainly because RMagick needs you to call GC.start after doing image related tasks to clean up C-bound <span class="caps">API</span> resources)</p>
<h2>Beware Of &#8216;Constants&#8217;</h2>
<p>Many people don&#8217;t seem to understand the constant semantics fully in Ruby. It is very easy when dealing with constants that are not simple data types to suffer from the same issues as I outlined as above.</p>
<h4>Example code</h4>
<code class="ruby">
<![CDATA[
class User < ActiveRecord::Base
  SEARCH_DEFAULTS = {
    :disabled => false,
    :suspended => false,
    # More criteria here
    }
  named_scope :some_search, :conditions => SEARCH_DEFAULTS
end

class UsersController < ApplicationController
  def search
    # Ignore the fact we our not using our named scope here
    @users = User.find(:all, :conditions => User::SEARCH_DEFAULTS.update(params))
  end
end

]]>
</code><p>Despite the fact <code>User::SEARCH_DEFAULTS</code> should be constant, it does not mean the contents of the <code>User::SEARCH_DEFAULTS</code> hash table is constant. This is because Ruby&#8217;s constants act much like the const type qualifier in C++. That is firstly if you want, you can explicitly override constants in a similar way that C++ can let you use const_cast to remove the &#8216;const&#8217; from a variable (Interestingly, Rails exploits the undef_const in it&#8217;s Dependency / class reloading system). Secondly, and most importantly in this case, is that only the reference to the object is constant, not the object it&#8217;s self. That is you can&#8217;t make SEARCH_DEFAULTS reference another object. However <strong>you can modify the object SEARCH_DEFAULTS points to</strong>. This will most likely trip you up when you are not using a simple data type such as a number, symbol, or maybe string. In the above example each search request will modify the <code>User::SEARCH_DEFAULTS</code> hash table. You need to be particularly careful here when using collection data types.</p>
<h3>Preventing This.</h3>
<p>There is a very simple fix to this. It&#8217;s called the <code>freeze</code> method. All we need to do is call <code>freeze</code> after defining the hash table. For example:</p>
<code class="ruby">
<![CDATA[
  SEARCH_DEFAULTS = {
    :disabled => false,
    :suspended => false,
    # More criteria here
    }.freeze
]]>
</code><p>This will ensure the hash table object is not mutable (modifiable). This therefore means that we need to update the UsersController#search method to call <code>.dup</code> after referencing <code>User::SEARCH_DEFAULTS</code> because the <code>Hash#update</code> method will modify the the receiver.</p>
<h2>Summary</h2>
<p>I hope this post will help others. As a seasoned Rails developer, I have to admit that even I got caught out a few months ago by one of the issues I outlined in this post. It goes to show how easy it is to overlook something when you are caught off-guard and are not coding in a defensive manor!</p>
<p>In my next post, I will probably cover some smaller more Rails centric issues that have managed to bite me when getting dirty with other peoples code when haven&#8217;t coded defensively.</p></div></content></entry><entry><updated>2008-08-16T00:35:20Z</updated><title>Overlooked Rails Best Practises Pt.1</title><id>http:///blog/overlooked_rails_best_practises_pt_1</id><content type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml"><h2>Why Yet Another Post?</h2>
<p>I know so many people go on about Rails based coding practises. However, it seems despite all this harping that other people do, there are a large numbers that are out of tune with this. It&#8217;s some what has got to me as I really hate getting involved in projects when there are no clear guidelines on coding style or practises, because as soon as several programmers with varying styles get involved things get unconformable for everyone.</p>
<p>The concept of &#8216;Best Practises&#8217; is certainly a very subjective issue. Certainly I will agree when it comes to basic code layout, there is no right or wrong way, likewise some of the points I will put here are going to be subjective, but this is what I think are some good starting points.</p>
<p>In this post, and probably some subsequent posts, I want to cover some basic principles that I personally think should be applied to all Rails projects as a form of defensive programming.</p>
<h2>Fixtures Considered Harmful</h2>
<p>I know some will think this is somewhat odd, but I hate fixtures with a passion. My problem with fixtures is that they generally tend to work on a global basis, and thus can manifest issues that are typical of programs that misuse global variables and other forms of undesired side effect created by a shared state.</p>
<h3>The Shared State Scenario</h3>
<p>A typical example that illustrates this is that you need to add or remove data to a set of fixtures in order to reflect a specific new feature you&#8217;ve just added. Because of the global nature of fixtures, many other tests that use that set of fixtures are at risk if breaking because you are sharing that data. These other tests are completely unrelated to changes you&#8217;ve made, and therefore are &#8216;leaky&#8217; in nature because they shouldn&#8217;t be failing as they are totally unrelated.</p>
<h3>Inefficient</h3>
<p>Another issue I have with fixtures is that they are not expressive. They seems to carry a lot of baggage that is not needed. For instance if I&#8217;m writing a test that relates to the billing of a property, I only am wanting to focus on fields such the price of the property and maybe some date specific stuff if the system is subscription based. Yet with fixtures you end up carrying a whole load of extra baggage for all the other fields.</p>
<p>What would be far better is to have some sort of base shared state, which basically is just used to set up the bare minimum defaults required for the given model. This would mainly be there to ensure things such as validations are kept happy. Each test can then then simply modify / update attributes to this base data. Personally, I think this is far more expressive. For example:</p>
<h4>A Possible Alternative To Fixtures</h4>
<code class="ruby">
<![CDATA[
# In your test helper or some other common/shared test code file you would define some example 
# model instances which can be used to encapsulate any necessary data that by design probably 
# needs to be shared. 
class ActiveRecord::Base
  def self.example(specifics = {})
    create! self::EXAMPLE_DEFAULTS.dup.update(specifics)
  end
end

# Each model would need to define some EXAMPLE_DEFAULTS. 
# You might want to DRY things up by placing this in a YAML file, while this is similar to a 
# fixture in the sense that is shared data, this is minimal data that is simply used to ensure 
# the model just 'behaves' (e.g. saves without validation issues, etc). However the difference 
# here is are not defining large number of instances in your DB, of which each test is probably
# only going to use a handful of these instances
class Property
  EXAMPLE_DEFAULTS = {
    :summary => 'My test property',
    :description => 'Please buy me!',
    :price => 450_000.usd,
    :market => 'Sale',
    :classification => 'Residential',
  }
end

class User
  EXAMPLE_DEFAULTS = {
    :login => 'jase',
    :password => 'dont ask me',
    :credit_balance => 0.usd,
  }
end

# ... etc for each model

# Now in your test cases you generate data on the fly rather than pull data from a fixture. 
# This way each test is only having to deal with data specific to the it's test case.
describe Property, 'billing' do
  attr_reader :property, :user

  before :each do
    # Note how we create each instance we need, overriding field relevant to what our 
    # test is going to cover
    @user = User.example :credit_balance => 50.usd
    @property = Property.example
  end

  it "should cost $10 to list a property" do
    property.active?.should be_false
    property.activate_listing!
    property.active?.should be_true
    user.credit_balance.should == 40.usd
  end

  # Put other related scenario examples here obviously
end

]]>
</code><p>Using the technique illustrated above we manage to <acronym title="Don&#39;t repeat yourself"><span class="caps">DRY</span></acronym> up our test data in a similar way that fixtures try to keep things <span class="caps">DRY</span> up common data between tests. This also gets round the issues highlighted in the &#8216;shared state scenario&#8217;. That is if we decide to rename/delete a field such as <code>User#credit_balance</code>, we only need to change code in test that use this field. In the case of modifying a field like <code>Property#summary</code>, which is shared (because it is required through the use of a validation) everywhere, we only need to change it in one place, thus keeping our code <span class="caps">DRY</span>, and avoiding the &#8216;leaky failing case&#8217; issue.</p>
<h3>Improving Code Coverage</h3>
<p>Not only does the above concept <span class="caps">DRY</span> up code and make it more robust, but we also improve our <a href="http://en.wikipedia.org/wiki/Code_coverage">code coverage</a> (If you haven&#8217;t heard of it, look at <a href="http://eigenclass.org/hiki.rb?rcov">RCov</a>). This is because we are using code to create our models code such as callbacks (i.e. before_create, after_create, etc) and validations will get called during our tests. Thus this helps reduce the flakiness of tests with very little extra effort.</p>
<h2>Closing Words</h2>
<p>Hopefully, I&#8217;ve illustrated the case why fixtures create brittle tests, and looked at a possible alternative style that addresses the major pitfalls incurred by using fixtures.</p>
<p>I&#8217;ll be planning to create a whole series of posts on this topic, so stay tuned.</p></div></content></entry><entry><updated>2008-08-11T04:23:40Z</updated><title>Cleaner RDoc Styles</title><id>http:///blog/cleaner_rdoc_styles</id><content type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml"><h2>Motivation</h2>
<p><a href="http://rdoc.sourceforge.net/">RDoc</a> is a really nice code-comment documentation generator to be honest, and compared to my experiences with other systems where you have to prefix ugly &#8216;@&#8217; symbols all over the place, along with do other nasty things like give type hints (in the cast of messy <span class="caps">PHP</span> which doesn&#8217;t seem to know if it should use C style weak typing or Java&#8217;s strong typing). However, I do think that nearly all doc-comment systems seem to have awful <span class="caps">CSS</span> styling by default.</p>
<p>Below is a cut and paste <span class="caps">CSS</span> style sheet you can use to replace the default rdoc-styles.css file. You also might want to replace the index.html file with the version I provide here if you want a left aligned frame-set like the <a href="http://api.rubyonrails.org/">Ruby on Rails <span class="caps">API</span> Docs</a></p>
<h2>Example Pages</h2>
<p>You probably want to take a peek to see what all the rage is about. Well I&#8217;m currently using these styles for the <a href="http://typeface.jasonearl.com/documentation/">TypeFace Documentation Site</a></p>
<h2>The Code</h2>
<p>Just copy and paste this, and use freely in your projects. Treat loosely it like <a href="http://creativecommons.org/licenses/by-sa/2.5/">Creative Commons Share Alike</a> license. If you can give me a link back to here, to spread the word, I&#8217;d be grateful, but it&#8217;s not required if you don&#8217;t want to. If you do use these, it would be nice to know that others have found my <span class="caps">CSS</span> useful, if want to <a href="mailto:jason@hybd.net">drop me an email</a> I&#8217;d be grateful, let me know the <span class="caps">URL</span> of your project if it&#8217;s on-line.</p>
<h4>index.html</h4>
<code class="html">
<![CDATA[
<!DOCTYPE html 
     PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
  <title>Rails Framework Documentation</title>
  <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>

<frameset cols="25%,*">
    <frameset rows="15%,35%,50%">
        <frame src="fr_file_index.html"   title="Files" name="Files" />
        <frame src="fr_class_index.html"  name="Classes" />

        <frame src="fr_method_index.html" name="Methods" />
    </frameset>
      <frame  src="files/doc/README_FOR_APP.html" name="docwin">
    <noframes>
          <body bgcolor="white">
            Click <a href="html/index.html">here</a> for a non-frames
            version of this page.
          </body>
    </noframes>
</frameset>

</html>
]]>
</code><h4>rdoc-styles.css</h4>
<code class="plain">
<![CDATA[
body {
  font-family: Verdana, Arial, Helvetica, sans-serif;
  font-size: 11px;
  padding: 0 16px;
  margin: 0;
  background: white;
  line-height: 1.7em;
}

h1,
h2,
h3,
h4 { 
  margin: 0; 
  color: white; 
  background: transparent; 
  font-family: "Arial Unicode MS", Verdana, Arial, Helvetica, sans-serif;
}
h1 { 
  font-size: 1.5em; 
}

h2,
h3,
h4 { 
  margin-top: 1em; 
}

h3 {
  font-size: 1.25em;
}

a { 
  color: #039; 
  text-decoration: none; 
}

a:hover { 
  color: #006;
  border-bottom: 1px solid #63abe9;
}

/* Override the base stylesheet's Anchor inside a table cell */
td > a {
  background: transparent;
  color: #039;
  text-decoration: none;
}

/* and inside a section title */
.section-title > a {
  background: transparent;
  color: #eee;
  text-decoration: none;
}

td {
  font-size: 11px;
}

/* === Structural elements =================================== */

div#index {
    margin: 0 -16px;
    padding: 0 0.7em;
    font-size: 0.9em;
    line-height: 1.4em;
}


div#index a {
    white-space: nowrap;
}

div#index a:hover {
  font-weight: bold;
}

div#index .section-bar {
   padding: 0.3em 0.7em;
   background: #ccc;
   font-size: 1.3em;
   margin: 0 -0.7em 0.5em -0.7em;
}

div#classHeader, div#fileHeader {
    width: auto;
    color: white;
    padding: 0.5em 1.5em 0.5em 1.5em;
    margin: 0 -16px;
    border-bottom: 3px solid #006;
}

div#classHeader a, div#fileHeader a {
    background: inherit;
    color: white;
}

div#classHeader td, div#fileHeader td {
    background: inherit;
    color: white;
}


div#fileHeader {
    background: #057;
}

div#classHeader {
    background: #048;
}

.header-table td {
  vertical-align: baseline;
  border: 0 none;
}

.class-name-in-header {
  font-size:  2.3em;
  font-weight: normal;
  font-weight: bold;
  font-family: "Arial Unicode MS", Verdana, Arial, Helvetica, sans-serif;
}


div#bodyContent {
    padding: 0;
    margin: 0;
}

div#description {
    padding: 1em 1em 0.5em 1em;
    background: #f8f8f8;
    border: 1px solid #ddd;
    margin: 2em 0 0 0;
}

div#description h1,h2,h3,h4,h5,h6 {
    color: #125;
    background: transparent;
}

div#description h1 {
    color: #004663;
    border-bottom: 1px solid #ddd;
    padding-bottom: 0.25em;
    font-weight: normal
}

div#validator-badges {
    text-align: center;
}
div#validator-badges img { border: 0; }

div#copyright {
    color: #333;
    background: #efefef;
    font: 0.75em sans-serif;
    margin-top: 5em;
    margin-bottom: 0;
    padding: 0.5em 2em;
}


/* === Classes =================================== */

table.header-table {
    color: white;
    font-size: 0.8em;
}

.type-note {
    font-size: 0.8em;
    color: #DEDEDE;
}

.xxsection-bar {
    background: #eee;
    color: #333;
    padding: 3px;
}

.section-bar {
   color: #333;
   border-bottom: 1px solid #999;
}


.section-title {
    background: #79a;
    color: #eee;
    padding: 3px;
    margin-top: 2em;
    margin-left: -30px;
    border: 1px solid #999;
}

table {
  border-collapse: collapse;
}

td {
  padding: 4px 20px 4px 0;
  border-bottom: 1px solid #eee;
}

.top-aligned-row {  vertical-align: top }
.bottom-aligned-row { vertical-align: bottom }

/* --- Context section classes ----------------------- */

.context-row { }
.context-item-name { font-family: monospace; font-weight: bold; color: black; }
.context-item-value { color: #448; }
.context-item-desc { color: #333;  }

/* --- Method classes -------------------------- */
.method-detail {
    background: #f8f8f8;
    padding: 0;
    margin-top: 0.5em;
    margin-bottom: 1em;
    border: 1px solid #ddd;
}
.method-heading {
  color: black;
  background: #ddd;
  border-bottom: 1px solid #ccc;
  padding: 0.2em 0.5em 0 0.5em;
}
.method-signature { color: black; background: inherit; }
.method-name { font-weight: bold; }
.method-args { font-style: italic; }
.method-description { padding: 0 0.5em 0 0.5em; }

/* --- Source code sections -------------------- */

a.source-toggle { font-size: 0.9em; }
div.method-source-code {
    background: black;
    color: #ffdead;
    margin: 1em 0;
    padding: 0 1em;
    border: 1px solid #999;
    overflow: hidden;
}

div.method-source-code pre { 
  color: #aaa; 
  overflow: hidden; 
  font-family: "Lucida Console", "Bitstream Vera Sans Mono", monospace;
}

/* --- Ruby keyword styles --------------------- */

.standalone-code { background: #221111; color: #ffdead; overflow: hidden; }

.ruby-constant  { color: #d00; background: transparent; font-weight: bold; }
.ruby-keyword { color: #f60; background: transparent; font-weight: bold; }
.ruby-ivar    { color: white; background: transparent; }
.ruby-operator  { color: #00ffea; background: transparent; }
.ruby-identifier { color: white; background: transparent; }
.ruby-node    { color: #fe6e34; background: transparent; }
.ruby-comment { color: #0e7e92; font-weight: bold; background: transparent; }
.ruby-regexp  { color: #ffa07a; background: transparent; }
.ruby-value   { color: #05dfdc; background: transparent; }
]]>
</code></div></content></entry><entry><updated>2008-08-10T17:54:53Z</updated><title>Experiments with VoIP + Ruby</title><id>http:///blog/experiments_with_voip_ruby</id><content type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml"><h2>Adhearsion &amp; Asterisk Overview</h2>
<p>In recent months there seems to be a bit of attention building up with a project called <a href="http://adhearsion.com">Adhearsion</a> which provides an excellent Ruby interface to the <a href="http://www.asterisk.org/">Asterisk VoIP</a> open source server. I discovered these projects last week while researching into a VoIP based project that might end up doing.</p>
<p>Adhearsion provides a very simple way to control login in telephony applications that are powered by Asterisk and it&#8217;s <span class="caps">AGI</span> <span class="caps">API</span>. This allows developers to create bespoke switchboards systems very easily and quickly. While phone switchboards are seen as an annoyance, you can do some very nice things, and the examples provided show how one can integrate this with external API&#8217;s, such as weather and stock quotes very quickly.</p>
<p>To add to the existing Adhearsion / Asterisk bindings, I was interested in the possibility of looking at text-to-speech synthesis, because by default Adhearsion can only play back pre-recorded sounds such as <span class="caps">GSM</span> files. Likewise, to complement this, I also wanted to see how viable it was to use basic speech-recognition. I&#8217;ve not looked deeply into this, but this is something I plan to look at and maybe do follow up post / presentation about at some point in the future.</p>
<h2>Using Text-To-Speech</h2>
<p>Festival <span class="caps">TTS</span>, which can be easily installed with most Redhat/Debian based systems provides a simple means for providing text-to-speech. There are also some basic <a href="http://festivaltts4r.rubyforge.org/">Ruby Bindings</a> which simply wrap round the command line festival command.</p>
<h2>Using Speech Recognition</h2>
<p>Speech recognition is not so easy. Phones generally only have a 8Khz signal, which means letters such as F and S can easily get mixed up due to the loss of sound quality. For accurate speech-to-text recognition, you really need 16Khz signals. However using a very limited vocabulary (utterance is the technical term), one can do some privative recognition via <span class="caps">CMU</span> Sphinx.</p>
<p>Again <span class="caps">CMU</span> Sphinx 2.x can be installed easily on Debian/Redhat based distros. Sphinx 4 however is Java based and needs be installed manually from the binary packages provided on the <a href="http://cmusphinx.sourceforge.net/"><span class="caps">CMU</span> Sphinx website</a>. If you are using Debian based distro&#8217;s you should be warned that it typically ships with the <span class="caps">CGJ</span> flavoured virtual machine which is much less efficient than the original Sun <span class="caps">JVM</span>, so you will want to do something like <code>sudo apt-get instal sun-java-bin</code> to resolve this.</p>
<p>Sphinx takes a while to load, so it would probably be best to setup some sort of daemon system, of which I have seen some <a href="http://www.voip-info.org/wiki/view/Sphinx">Perl scripts</a> for that might work.</p>
<h2>Summary</h2>
<p>While I&#8217;ve not covered anything in detail, if anyone is having to do a similar project, it might help point them in the right place. If there are people who want to know more (or know more and would like to collaborate with me on a possible tutorial) please give me a shout at <a href="mailto:jason@hybd.net">jason <del>at</del> hybd <del>dot</del> net</a>. If a number of people are interested, it would certainly motivate me to do a detailed post regarding the topic.</p></div></content></entry><entry><updated>2008-08-07T02:56:07Z</updated><title>Creating 'S5' RedCloth Presentations</title><id>http:///blog/creating_s5_redcloth_presentations</id><content type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml"><h2>Overview</h2>
<p>As you may gather, I&#8217;ve been abusing RedCloth a lot recently, which is also reflected by the fact I&#8217;ve submitted a number of bug reports before the official release and a couple of small patches.</p>
<p>Like the old 3.x branch, you can create custom block commands. However due to the C/Ragel based parser the implementation details are incompatible. I&#8217;m going to illustrate how we can use <a href="http://meyerweb.com/eric/tools/s5/">Eric Meyer&#8217;s S5</a> tool for making <span class="caps">XHTML</span> based presentations and combine that with the new RedCloth 4.x formatter system in order to extend on the existing Textile mark-up system.</p>
<h2>The Implementation</h2>
<h3>New Textile Commands</h3>
<p>RedCloth 4.x can support custom block items thanks to a patch added by <a href="http://webby.rubyforge.org/">Tim Pease</a>. Basically what we are going to do is make a new module that will provide two extra commands, <strong>slide</strong> and <strong>annotation</strong> to the existing Textile system when rendering to S5 format. This is done by having methods called <code>slide</code> and <code>annotation</code> in our custom formatter module. All block commands accept a hash table instance which contains any optional attributes and the block text (with in-line Textile commands pre processed). The S5 formatter is basically an extension of <span class="caps">HTML</span> formatting and you will see how we inherit the same formatting support though the <code>include</code> directive.</p>
<h4>S5 Redcloth Formatter Code Listing</h4>
<code class="ruby">
<![CDATA[
require 'rubygems'
require 'redcloth'
require 'erb'

module RedCloth
  # Patch up with a handy to_s5 method.
  class TextileDoc
    
    attr_accessor :settings
    
    def to_s5(*config)
      self.settings = config.last.is_a?(Hash) ? config.pop : {}
      apply_rules config
      to RedCloth::Formatters::S5
    end
  end
  
  # = S5 Based XHTML Formatter
  #
  # Based on the S5 system at http://meyerweb.com/eric/tools/s5/ this derives 
  # from the HTML formatter to provide a basic slide 
  module Formatters::S5
    
    include RedCloth::Formatters::HTML, ERB::Util
    attr_reader :settings
    
    def render(scope = nil, template_file = nil)
      template_file ||= settings[:template] || 'default.html.erb'
      template_data   = File.read template_file
      code = ERB.new template_data, nil, '-'
      render_template code, scope
    end
    
    def render_template(code, scope = nil)
      scope ||= binding
      eval code.src, scope
    end
    
    def slide(opts)
      slide_end + "\n\n" + slide_start(opts) + "\n"
    end
    
    def after_transform(text)
      content = text
      content << slide_end if @slides_used
      text[0..-1] = render binding # Replacement hack!
    end
    
    def slide_start(opts = {})
      @slides_used  ||= true
      (opts[:class] ||= '') << ' slide'
      %[<div#{pba opts}><h1>#{h opts[:text]}</h1><div class="slidecontent">]
    end
    
    def annotation(opts)
      '</div><div class="handout">' + opts[:text].to_s
    end
    
    def slide_end
      '</div></div>'
    end
  end
end
]]>
</code><p>In order to allow for customisation of the main S5 mark-up, I will use <span class="caps">ERB</span> (as it&#8217;s comes with Ruby) to do this. When rendering to S5 format using <code>RedCloth#to_s5</code> instead of <code>RedCloth#to_html</code> we can provide additional details such as the author, template file, a custom footer, etc.</p>
<p>As you will see most of the code is in a single module which as a few <span class="caps">ERB</span> helper methods, we include <code>ERB::Util</code> too so our template can use methods such as <code>h</code> and <code>u</code>.</p>
<p>You may see that I&#8217;m doing something particularly odd with the <code>after_transform</code> call back method. Basically the processed text is passed to it as a parameter and needs to be treated with reference semantics, despite the fact strings normally use value semantics by default in most scripting languages such as Ruby. If your from a C/C++ background, this will be a fairly normal idiom. Basically, you need to <strong>modify actual the contents</strong> of text parameter, rather than return a modified version. This is most probably because it was easier from an implementation point of view, and is marginally faster I&#8217;m guessing.</p>
<h2>Usage.</h2>
<p>Typically, you should be able to do something like:</p>
<code class="ruby">
<![CDATA[
slide_show = <<-TEXT
slide. Hello 1

p. This is the first slide! 

p. Notice how the slide block contents are made into the slide header.

slide. Hello 2

p. This is the second slide content

* Here is a very ...
* Basic example of a ...
* Bullet List.

annotation. 
This is only shown on printed versions and not on display versions. 
Annotations can help act as guides or printed hand out content.

slide(third #item). Hello 3

p. This is the third slide content
TEXT

show = RedCloth.new(slide_show).to_s5 \
  :title  => 'S5 on Red Cloth Example',
  :author => 'Jason Earl',
  :footer => 'Custom footer content can go here'
]]>
</code><h2>Support Files</h2>
<p>By default the <code>RedCloth#to_s5</code> method will look for a <strong>default.html.erb</strong> file in the current folder. You might want to change the location of this. You will probably want to save the result of the <code>RedCloth#to_s5</code> method somewhere. This should have a sub folder containing the <strong>ui/default</strong> files from the original S5 package, as this contains <span class="caps">CSS</span> and JavaScript files that control the presentation system.</p>
<h4>Sample default.html.erb</h4>
<p>You can use this as a starting point / default template for S5 presentations. This needs to be in the same folder as the S5 formatter module.</p>
<code class="html">
<![CDATA[
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 
	"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
<title><%= h settings[:title] %></title>
<!-- metadata -->
<meta name="generator" content="S5" />
<meta name="version" content="S5 1.1" />
<meta name="presdate" content="<%= Time.now.strftime('%Y%m%d') %>" />
<% if settings[:author] %>
<meta name="author" content="<%= h settings[:author] %>" />
<% end %>
<% if settings[:company] %>
<meta name="company" content="<%= h settings[:company] %>" />
<% end %>
<!-- configuration parameters -->
<meta name="defaultView" content="slideshow" />
<meta name="controlVis" content="hidden" />
<!-- style sheet links -->
<link rel="stylesheet" href="ui/default/slides.css" type="text/css" media="projection" id="slideProj" />
<link rel="stylesheet" href="ui/default/outline.css" type="text/css" media="screen" id="outlineStyle" />
<link rel="stylesheet" href="ui/default/print.css" type="text/css" media="print" id="slidePrint" />
<link rel="stylesheet" href="ui/default/opera.css" type="text/css" media="projection" id="operaFix" />
<!-- S5 JS -->
<script src="ui/default/slides.js" type="text/javascript"></script>
</head>
<body>

<div class="layout">
<div id="controls"><!-- DO NOT EDIT --></div>
<div id="currentSlide"><!-- DO NOT EDIT --></div>
<div id="header"></div>
<div id="footer">
<%= RedCloth.new(settings[:footer].to_s).to_html %>
</div>
</div>

<div class="presentation">
<%= content %>
</div>

</body>
</html>
]]>
</code><h2>Closing Words</h2>
<p>Hopefully someone has found this a handy concept, and maybe has given others some idea how they can make their own extensions to RedCloth 4.x through the new formatter system. One of the nice things is that if you use an other formatter, the <code>annotation</code> and <code>slide</code> commands will simply be ignored and be rendered though the paragraph fallback, thus the case of generic <span class="caps">XHTML</span> formatting, will appear as a <code>p</code> tag. Obviously, one can use textile class names and custom <span class="caps">CSS</span> to control how these get displayed in other formats.</p>
<p>Between mocking this up and writing this post, I realised that there is a <a href="http://slideshow.rubyforge.org/">slideshow gem</a> on <a href="http://rubyforge.org/">RubyForge</a> that works in a similar way. Slideshow offers some <span class="caps">SVG</span> graphics support which would be handy given the dynamic nature of screen resolutions.</p></div></content></entry><entry><updated>2008-08-11T14:25:24Z</updated><title>Testing Time Dependent Code</title><id>http:///blog/testing_time_dependent_code</id><content type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml"><h2>The Problem</h2>
<p>Writing unit tests is a great way to ensure your code works and ensure that other programmers don&#8217;t break your code by accident. Not only that the whole testing philosophy seems to encourage you to think about making your code as modular as possible in order to be make it testable, thus making it more robust architecturally.</p>
<p>However, difficulties often seem to arise with when testing pieces of code that are strongly associated to any sort of I/O with external systems, or anything else that is tied to some sort of global side effect, such systems need to use randomisation or has time dependencies. Over the years most test frameworks have managed to over come these issues through the use of <a href="http://en.wikipedia.org/wiki/Mock_object">Mock Objects</a>.</p>
<p>One issue though seems to haunt me a lot is dealing with systems which trigger events based on the system time. For instance credit based billing systems where the amount you pay for a service is based on the amount of time you actively use it. A good example would be property website where users will get billed a fixed amount for each active property that have listed on a monthly basis. In a test scenario we need to be able create a property, and simulate going into future by a set period of time and ensure that our system is able to pick up and bill our user for the time period we&#8217;ve moved forward by.</p>
<h2>A Possible Solution</h2>
<p>Thankfully, Ruby&#8217;s dynamic ability to override core features allows us to rewrite how the Time class behaves in a test environment. This can easily be done by making the Time.now method return a different time if we have decided to manually override the time. A piece of sample code you could use for in your Test/Spec helpers might be:</p>
<h4>Source Listing:</h4>
<code class="ruby">
<![CDATA[
class Time
  # Holds the fake times
  @@active = nil
  cattr_accessor :active

  class << self
    # Return fake time if the time has been overriden
    def now
      active || new
    end
    
    # Set the time to be fake for a given block of code
    def is(new_time, &code)
      old_time = active
      self.active = new_time
      begin
        code.call if code
      ensure
        self.active = old_time
      end
    end
  end
end
]]>
</code><h3>How It Works</h3>
<p>This code should be fairly simple to understand for those who know Ruby. Basically we use a class variable to hold the overridden time value. If this is not set it will get it from the system clock via the <code>Time.new</code> method which does the same thing as the old <code>Time.now</code> method. While we can override the time using the class writer for <code>Time.active=</code>, it is preferable that we use <code>Time.is</code> as this protects us from possible control flow issues that arise from not resetting the time back if pre maturely exit our code, either by accident through programmer error (i.e. returning from a function), or because of an Exception / failed test case. The use of blocks + ensure handles this in a similar way to <a href="http://en.wikipedia.org/wiki/Resource_Acquisition_Is_Initialization"><span class="caps">RAII</span> in C++</a>.</p>
<h2>Example Usage</h2>
<p>As stated above, we should protect ourselves by using the <code>Time.is</code> method in critical areas, or at least use <code>Time.active = nil</code> in the tear down process of our test, otherwise we run the risk of affecting other our test cases incorrectly.</p>
<p>Below shows a basic pseudo code example for the property scenario I outlined earlier:</p>
<code class="ruby">
<![CDATA[
property = Property.create # Put our attributes here
property.months_billed.should == 1
Time.is 3.months.since do
  property.bill!
  Time.active = 1.hour.since
  property.months_billed.should == 4
end
]]>
</code></div></content></entry><entry><updated>2008-08-09T19:25:32Z</updated><title>LaTeX/PDF formatting in RedCloth4</title><id>http:///blog/latex_pdf_formatting_in_redcloth4</id><content type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml"><h2>About RedCloth</h2>
<p>Due to the various issues with the old RedCloth 3.x branch I was one of the early adopters of <a href="http://github.com/jgarber/redcloth/tree/master">RedCloth 4</a>. RedCloth is a Ruby implementation of the <a href="http://www.textism.com/tools/textile/">Textile</a> mark up / micro language for text formatting. For those who don&#8217;t know, Textile is a lightweight alternative to <span class="caps">XHTML</span> which is often used on the web in place of <span class="caps">WYSIWYG</span> <span class="caps">HTML</span> editors, mainly because it is simple and makes it easy to filter the text so there is no harmful (i.e. libale to <span class="caps">XSS</span> attack through injecting <span class="caps">SCRIPT</span> tags) or bad (i.e. Anything pasted from Micro$oft Office).</p>
<h2>Differences From Version 3.x</h2>
<p>RedCloth 4 should be a lot faster, while eliminating most of the bugs known in  On top of this it has very basic support for LaTeX and a simple system for support custom formatters. This proves to be very handy for me as I can use Textile both for web pages and <span class="caps">PDF</span> documents in a seamless way.</p>
<h2>Creating PDF&#8217;s</h2>
<p>Here&#8217;s the nitty gritty details for those wanting to render PDF&#8217;s in Textile, here&#8217;s a quick summary how to do it.</p>
<ul>
	<li>Install Tetex/pdflatex, instructions will vary for this according to what distro / operating system you use. In Debian/Ubuntu you can use <code>sudo apt-get install texlive</code></li>
	<li>Install the latest RedCloth, using <code>gem install RedCloth</code>. You will need a C compiler installed for this, and note the capitalisation of the package name.</li>
</ul>
<p>Using the following code as a starting point / example, you should be get a basic <span class="caps">PDF</span> rendered:</p>
<code class="ruby"> 
<![CDATA[
require 'rubygems'
require 'redcloth'
text = 
  "h1. Here is a test heading\n\n" + 
  "p. Here is some paragraph content. " + 
  "Obviously you will want to change this text."
latex = RedCloth.new(text).to_latex
tex_document = 
  "\\documentclass[a4paper]{article}" +
  "\\RequirePackage{graphicx}" +
  "\\RequirePackage{hyperref}" +
  "\\author{ Site Author }" +
  "\\date{Published Date}" +
  "\\title{Site Name Here}" +
  "\\pagestyle{headings}" +
  "\\begin{document}" +
  "\\maketitle" +
  "\\newpage" +
  "#{latex}" +
  "\\end{document}"
File.open "latex_test.tex", "wb" do |file|
  file.write tex_document
end
system "pdflatex latex_test.tex"
]]>
</code><p>As you can gather we need to generate a bit of extra meta data after call the to_latex method to let pdflatex know how to format things on the page. The resulting <span class="caps">PDF</span> will be in your home folder, again this will probably need to change to somewhere different, however this puts across the main points across for getting <span class="caps">PDF</span> documents out of RedCloth using Textile.</p>
<p>Also note that images are not fully supported at the moment.</p></div></content></entry><entry><updated>2008-06-25T15:32:47Z</updated><title>Ditching Subversion in favour of Git!</title><id>http:///blog/ditching_subversion_in_favour_of_git_</id><content type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml"><p>While I&#8217;ve never really had issues with Subversion, I&#8217;ve always used it in a very closed environment where the centralised work flow never was an issue. However with the release of TypeFace, and the general raving in the Rails and Linux Kernel communities regarding <a href="http://git.or.cz/">Git</a>, it&#8217;s hard to ignore it.</p>
<h2>Personal Advantages &#8230;</h2>
<p>Having watched an <a href="http://www.youtube.com/watch?v=4XpnKHJAok8">excellent tongue &#8217;n cheek presentation by Linus</a>, I have to say I very quickly sold by it considering Linus is no marketing guy!</p>
<p>One of the interesting things about Git is that it completely changes your work flow and you suddenly find your self with a lot more freedom. Even if you are a solo coder, or still choose to flow the centralised model you were using under Subversion, you find that the ability to commit locally means that you commit more often because you don&#8217;t have to worry about making sure your code is &#8216;stable&#8217; or &#8216;passes all the unit tests&#8217; until you push it to the centralised system or someone else needs to pull from you. The increased commit rate makes a big allows everyone to have more up to date copies, which in turn avoids conflicts and saves merging. Certainly for <span class="caps">OSS</span> applications this a huge improvement as it encourages people to fork code and experiment now that merging is not such a chore.</p>
<p>Anyone using Subversion should seriously consider the switch. While there seem to be a number of nice distributed version control systems out there such as Darcs, and Bzr, it does seem like Git is showing it&#8217;s self to be one of the most superior. I prefer using <code>.gitinore</code> files to control ignored files rather than running <code>svn propedit svn:ingore {folder}</code> all over the place with new projects. The <code>.gitignore</code> file can easily be copied from project to project in the case of Rails projects.</p>
<h3>Other Advantages</h3>
<p>There are tonnes of other cool features I haven&#8217;t discovered or reported on here; such as the ability to track code throughout the project is great. For instance git can tell if you move a function from one file to another because it &#8216;sees content, not files&#8217; in the words of Linus. Likewise easy email patch generation, and the lack of <code>.svn</code> files being littered in each folder are a couple of others that spring to mind. (This is so handy as I often use grep to search through code, and hated all the annoying contents of .svn being reported by default).</p>
<h2>Windows Warning</h2>
<p>If you use Windows, you probably need to use Cygwin for now until native binaries emerge. Also, the only thing I have found frustrating is that files that get end up getting the odd <span class="caps">DOS</span> style <span class="caps">CRLF</span> line ending in them later seem to make git moan about patching or something. I found the easy way round this was to use <code>git config --global core.autocrlf=input</code> (only needs to be one once on your computer) and turn off precommit hooks using <code>git commit --no-verify</code> when git complains. This global <span class="caps">CRLF</span> setting will ensure <span class="caps">DOS</span> line endings are only converted on input. Ideally if you use Windows, you should be using an editor like UltraEdit which allows you to edit in <span class="caps">UNIX</span> mode by default.</p></div></content></entry><entry><updated>2008-06-25T15:22:55Z</updated><title>First TypeFace Release</title><id>http:///blog/first_typeface_release</id><content type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml"><p>At long last I&#8217;ve finally got round to releasing TypeFace. While this initial release is still pretty rough on the edges, any reasonable Rails developer who is prepared to pick about a bit with the source should be able to do something with it.</p>
<p>Creating documentation and general tidying up has take a lot longer than expected. Documentation is still not great either. I plan to commit a few hours most days towards the project in order to make it more polished over time.</p>
<p>Expect some more regular posts on here relating to project in due course! You can find out more from <a href="http://typeface.jasonearl.com">by clicking here to go to the project page</a></p></div></content></entry><entry><updated>2008-06-20T18:58:30Z</updated><title>TypeFace Publisher Released Soon</title><id>http:///blog/typeface_publisher_released_soon</id><content type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml"><p>For those who haven&#8217;t seen in my <a href="../portfolio/index.html">portfolio</a>, <a href="../portfolio/typeface_publisher/index.html">TypeFace</a> is a publishing system I wrote which I use to power a few websites. It&#8217;s ideally suited for static websites where the client needs a nice web user interface for updating their website.</p>
<p>I will warn the first release will be <strong>very</strong> rough. There will be bugs, and documentation will be poor. However, anyone with reasonable Rails skills should be able to make use of it. I would really like feedback from others as I will do my best to maintain it. All I need to do is get some time to create some documentation, create an example &#8216;site&#8217; for people to get their hands dirty and clean up a few things in the interface.</p>
<p>As stated on the portfolio, the main advantage with TypeFace over most of the open source <span class="caps">CMS</span> systems out there is that it doesn&#8217;t require you to install it on the site&#8217;s web server as it generated content. This means you don&#8217;t have the issue of having to suddenly migrate the rest of your site round the architecture of the <span class="caps">CMS</span> like you do with other popular systems like Drupal, <span class="caps">XOOPS</span>, etc which require extra functionality to be implemented using their plug-in systems.</p>
<p>This will be my first serious contribution to back to the Open Source model. As strong supporter in the Open Source model, I think there is real value in programmers managing their own <span class="caps">OSS</span> projects. Not just for the <span class="caps">OSS</span> community, but it has many personal plus points:</p>
<ul>
	<li>Improves coding ability. It puts you under the scrutiny of other developers!</li>
	<li>Shows motivational skills</li>
	<li>Great way to easily gain project management skills</li>
	<li>Good way to establish your name in the community</li>
	<li>Sense of self-reward!</li>
</ul>
<p><a href="http://typeface.jasonearl.com"><strong>The new TypeFace site will be going live over the next few days over here</strong></a></p></div></content></entry><entry><updated>2008-06-25T15:23:05Z</updated><title>Finally, A Brand New Shiny Blog!</title><id>http:///blog/finally_a_brand_new_shiny_blog_</id><content type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml"><p>Despite being involved in web development on-and-off in the last 4 years  my life, I have managed to somehow shy away from setting up a blog of any sort. I did have a few very mediocre attempts, which never managed to get past my development environment.</p>
<p>Anyhow, I will do my best to keep this updated with the various thoughts, ideas and events relating to computing in my life. It will probably end up being very much a mash-up between web and games development articles.</p>
<p>The blog system I use at the moment is a very basic home-brew thing which still needs comments support added to it. Maybe in another 4 years I get round to implementing that!</p></div></content></entry></feed>