<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
 <title>blog.josh-nesbitt.net</title>
 <link href="http://feeds.feedburner.com/joshnesbittblog" rel="self"/>
 <link href="http://blog.josh-nesbitt.net"/>
 <updated>2010-05-06T20:06:30+01:00</updated>
 <id>http://blog.josh-nesbitt.net</id>
 <author>
   <name>Josh Nesbitt</name>
   <email>hello@josh-nesbitt.net</email>
 </author>
 
 <entry>
   <title>Simple database backups using a nightly CRON job and Capistrano</title>
   <link href="http://blog.josh-nesbitt.net/2010/05/06/simple-database-backups-using-a-nightly-cron-job-and-capistrano/"/>
   <updated>2010-05-06T00:00:00+01:00</updated>
   <id>http://blog.josh-nesbitt.net/2010/05/06/simple-database-backups-using-a-nightly-cron-job-and-capistrano</id>
   <content type="html">&lt;p&gt;&lt;a href=&quot;http://github.com/thoughtbot/limerick_rake&quot;&gt;Limerick Rake&lt;/a&gt; by &lt;a href=&quot;http://thoughtbot.com&quot;&gt;Thoughbot&lt;/a&gt; provides a useful set of Rake tasks to help simplify common tasks. One that I use quite a lot is the backup task which performs a &lt;code&gt;mysqldump&lt;/code&gt; of the specified environments&amp;#8217; database. It looks roughly like this:&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;brush: ruby;&quot;&gt;
# http://github.com/thoughtbot/limerick_rake/blob/master/tasks/backup.rake
# lib/tasks/backup.rake
namespace :application do
  desc &quot;Backs the applications database up for the given environment&quot;
  task :backup =&amp;gt; :environment do
    
    config           = ActiveRecord::Base.configurations[RAILS_ENV || 'development']
    database         = config['database']
    filename         = &quot;#{database.gsub(/_/, '-')}-#{Time.now.strftime('%Y-%m-%d-%H%M%S')}.sql&quot;
    backup_directory = File.expand_path(File.join(RAILS_ROOT, '..', '..', &quot;shared&quot;, &quot;backups&quot;))
    backup_path      = File.join(backup_directory, filename)
    binary           = %x[ which mysqldump ].strip
    
    options   =  &quot;-e -u #{config['username']}&quot;
    options   += &quot; -p#{config['password']}&quot; if config['password']
    options   += &quot; -h #{config['host']}&quot;    if config['host']
    
    raise RuntimeError, &quot;I only work with mysql.&quot; unless config['adapter'] == 'mysql'
    raise RuntimeError, &quot;Cannot find mysqldump.&quot; if binary.blank?
    
    FileUtils.mkdir_p(backup_directory)
    
    puts &quot;Backing up #{database}&quot;
    %x[ #{binary} #{options} #{database} &amp;gt; #{backup_path} ]
    puts &quot;Backed up #{database} =&amp;gt; #{backup_path}&quot;
    
  end
end
&lt;/pre&gt;
&lt;p&gt;There&amp;#8217;s a couple of ways I like to use this. Firstly, to ensure that the database is cloned before a deploy using &lt;a href=&quot;http://www.capify.org/index.php/Capistrano&quot;&gt;Capistrano&lt;/a&gt;. By hooking it into a &lt;code&gt;before&lt;/code&gt; callback I can ensure the database is backed up before any code is updated:&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;brush: ruby;&quot;&gt;
# config/deploy.rb
namespace :deploy do
  before &quot;deploy:update_code&quot;, &quot;deploy:backup&quot;

  desc &quot;Backs up the applications database to RAILS_ROOT/../shared/backups&quot;
  task :backup do
    run &quot;cd #{deploy_to}current &amp;amp;&amp;amp; rake application:backup RAILS_ENV=#{rails_env}&quot;
  end
end
&lt;/pre&gt;
&lt;p&gt;This does the job for small to medium sized sites, larger ones would have much more rigourous backup procedures. Another way is to use it on a nightly &lt;span class=&quot;caps&quot;&gt;CRON&lt;/span&gt; job, which might be more useful for preserving day-to-day snapshots of your database. In your crontab:&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;brush: plain;&quot;&gt;
0 1 * * * cd /path/to/project &amp;amp;&amp;amp; RAILS_ENV=production /usr/bin/env rake application:backup &amp;gt;&amp;gt; log/backup.log 2&amp;gt;&amp;amp;1
&lt;/pre&gt;
&lt;p&gt;This way you cover your back between deploys and keep daily copies of the database should the worse ever happen.&lt;/p&gt;</content>
 </entry>
 
 <entry>
   <title>iPhone 4.0 OS and developer choice</title>
   <link href="http://blog.josh-nesbitt.net/2010/04/12/iphone-40-os-and-developer-choice/"/>
   <updated>2010-04-12T00:00:00+01:00</updated>
   <id>http://blog.josh-nesbitt.net/2010/04/12/iphone-40-os-and-developer-choice</id>
   <content type="html">&lt;p&gt;There is currently a massive hoo haa within the iPhone and iPad developer community surrounding Apple&amp;#8217;s recent disclosure of requiring iP(hone/ad/od) applications (distributed on the app store) to be developed in Objective-C, C, C++, or JavaScript (as executed by the iPhone OS WebKit engine). In particular this implicitly highlights the barred usage of Adobe Flash to Objective C language compilers.&lt;/p&gt;
&lt;blockquote&gt;
3.3.1 — Applications may only use Documented APIs in the manner prescribed by Apple and must not use or call any private APIs. Applications must be originally written in Objective-C, C, C++, or JavaScript as executed by the iPhone OS WebKit engine, and only code written in C, C++, and Objective-C may compile and directly link against the Documented APIs (e.g., Applications that link to Documented APIs through an intermediary translation or compatibility layer or tool are prohibited).
&lt;/blockquote&gt;
&lt;p&gt;There have been &lt;a href=&quot;http://daringfireball.net/2010/04/iphone_agreement_bans_flash_compiler&quot;&gt;many&lt;/a&gt; &lt;a href=&quot;http://whydoeseverythingsuck.com/2010/04/steve-jobs-has-just-gone-mad.html&quot;&gt;takes&lt;/a&gt; on the matter, all with valid opinions.&lt;/p&gt;
&lt;p&gt;However, one point that I feel people are missing is the ongoing issue with the app store development/release process and static downloadable application binaries. People are worried about these restrictions enforced by Apple crushing their personal choice of language by locking them in to using only a select few languages for the development process. In a way I&amp;#8217;m not suprised Apple are doing this, however you look at it Apple are creating a closed environment for them to capitalise as best as they can on the dominance of their very popular platform. They want to do this in a way that applications distributed on the platform are unique to that platform, a niche application on an iPad is &lt;a href=&quot;http://culturedcode.com/things/ipad/&quot;&gt;another reason&lt;/a&gt; to &lt;em&gt;get&lt;/em&gt; an iPad.&lt;/p&gt;
&lt;p&gt;For quite a few applications the web (as a platform) would suffice. A lot of apps don&amp;#8217;t need access to these private API&amp;#8217;s, multi tasking abilities or &lt;em&gt;{insert other feature here}&lt;/em&gt; as a reason to choose the native application development path. I for one see this as a ongoing point that developers are free to harness the web as a platform for these devices, where there is &lt;del&gt;little&lt;/del&gt; no chance of being locked into a corner. When the dust has cleared I&amp;#8217;m sure we&amp;#8217;ll all move on and find a way to make these platforms work in our favour, &lt;a href=&quot;http://almost.done21.com/2010/04/adlib-apples-secret-ipad-web-framework/&quot;&gt;whatever route we take&lt;/a&gt;.&lt;/p&gt;</content>
 </entry>
 
 <entry>
   <title>Introducing Configr, an elegant configuration interface in Ruby</title>
   <link href="http://blog.josh-nesbitt.net/2010/03/01/introducing-configr-an-elegant-configuration-interface-in-ruby/"/>
   <updated>2010-03-01T00:00:00+00:00</updated>
   <id>http://blog.josh-nesbitt.net/2010/03/01/introducing-configr-an-elegant-configuration-interface-in-ruby</id>
   <content type="html">&lt;p&gt;I&amp;#8217;ve never really been happy with my &lt;a href=&quot;/2009/11/11/go-configure/&quot;&gt;previous solution&lt;/a&gt; to making configuration easy and elegant. It still felt too clunky and lacked the syntactical sugar that I&amp;#8217;ve become accustomed to within Ruby. So &lt;code&gt;configr&lt;/code&gt; was born.&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;http://rubygems.org/gems/configr&quot;&gt;Configr&lt;/a&gt; aims to provide a clean interface for configuring and reading a set of configuration values. The idea evolved from using a standard hash as a configuration store into a more elegant way to declare and read values from within a hash.&lt;/p&gt;
&lt;p&gt;I wanted a way to be able to declare my configurations in a simple format, whether that be inline (in the format of a block), from a &lt;span class=&quot;caps&quot;&gt;YAML&lt;/span&gt; file or as a mixture of the two. I also wanted to be able to have a simple way of overriding values for certain environments (for frameworks such as &lt;a href=&quot;http://www.sinatrarb.com/&quot;&gt;Sinatra&lt;/a&gt; and &lt;a href=&quot;http://rubyonrails.org/&quot;&gt;Rails&lt;/a&gt;). The project is far from done but it&amp;#8217;s the start of a more elegant solution to these problems over my previous method (simple hash based configuration).&lt;/p&gt;
&lt;p&gt;Using Configr is simple:&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;brush: ruby;&quot;&gt;
  configuration = Configr::Configuration.configure do |config|
    config.example_one = &quot;One&quot;
    config.example_two = &quot;Two&quot;
  end

  puts configuration.example_one
  puts configuration.example_two
&lt;/pre&gt;
&lt;p&gt;Declaring values inline is great, but its also useful to pull them in from a &lt;span class=&quot;caps&quot;&gt;YAML&lt;/span&gt; file:&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;brush: ruby;&quot;&gt;
  configuration = Configr::Configuration.configure(&quot;/path/to/file.yml&quot;)

  puts configuration.value_one
  puts configuration.value_two
&lt;/pre&gt;
&lt;p&gt;Or as a &lt;span class=&quot;caps&quot;&gt;YAML&lt;/span&gt; string:&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;brush: ruby;&quot;&gt;
  yaml = &amp;lt;&amp;lt;YAML

  example_one: &quot;Hello&quot;
  example_two: &quot;It loads from YAML too!&quot;
  
  YAML
  
  configuration = Configr::Configuration.configure(yaml)

  puts configuration.example_one
  puts configuration.example_two
&lt;/pre&gt;
&lt;p&gt;Or a mixture of both methods:&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;brush: ruby;&quot;&gt;
  yaml = &amp;lt;&amp;lt;YAML

  example_three: &quot;three&quot;
  example_four: &quot;four&quot;
  
  YAML
  
  configuration = Configr::Configuration.configure(yaml) do |config|
    config.example_one = &quot;one&quot;
    config.example_two = &quot;two&quot;
  end
  
  puts configuration.example_one
  puts configuration.example_two
  puts configuration.example_three
  puts configuration.example_four
&lt;/pre&gt;
&lt;p&gt;The idea is for Configr to be quite flexible in how you declare your configurations. The end result being able to read them in a more natural format:&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;brush: ruby;&quot;&gt;
  puts configuration.one.two.three
&lt;/pre&gt;
&lt;p&gt;Sometimes when using configuration values you might want to assert whether the value exists before using it. Configr allows you to do this with the &lt;code&gt;#key_name?&lt;/code&gt; syntax:&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;brush: ruby;&quot;&gt;
  puts configuration.one.two.three? # =&amp;gt; true
&lt;/pre&gt;
&lt;p&gt;Configr is intended to be framework agnostic, but it&amp;#8217;s easy to get it going inside of any of the latest frameworks. I don&amp;#8217;t plan to provide any &amp;#8220;out of the box&amp;#8221; way to hook Configr into Rails but it&amp;#8217;s easy to implement:&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;brush: ruby;&quot;&gt;
  # In config/configuration.rb
  yaml_file = Rails.root.join(&quot;config&quot;, &quot;environments&quot;, &quot;#{Rails.env}.yml&quot;)
  
  Configuration = Configr::Configuration.configure(yaml_file) do |config|
    config.my.configuration.value = &quot;value&quot;
  end
  
  # In config/initializers/configuration.rb
  require Rails.root.join(&quot;config&quot;, &quot;configuration.rb&quot;)
  
  # Anywhere in your Rails app
  Configuration.my.configuration.value
&lt;/pre&gt;
&lt;p&gt;By requiring a different &lt;span class=&quot;caps&quot;&gt;YAML&lt;/span&gt; file based on the environment it is easy to override global values with environment specific ones. For more examples of using Configr with other frameworks see &lt;a href=&quot;http://github.com/joshnesbitt/configr/blob/master/readme.rdoc&quot;&gt;the readme&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;By design a configuration value is not meant to be edited or created after the configuration block has been run (if you do you will run into a &lt;code&gt;Configr::ConfigurationLocked&lt;/code&gt; error). In my opinion configurations such as those created by Configr are meant to be read-only during the lifetime of the application.&lt;/p&gt;
&lt;p&gt;The gem is now available on &lt;a href=&quot;http://rubygems.org/gems/configr&quot;&gt;rubygems.org&lt;/a&gt;:&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;brush: ruby;&quot;&gt;
  gem install configr
&lt;/pre&gt;
&lt;p&gt;It&amp;#8217;s still early days for the project but I&amp;#8217;m already enjoying using it in a few personal and client projects, for me it certainly beats the previous method. If you use it and find any bugs please &lt;a href=&quot;http://github.com/joshnesbitt/configr/issues&quot;&gt;file an issue&lt;/a&gt; to help me wean out any problems.&lt;/p&gt;</content>
 </entry>
 
 <entry>
   <title>Lockfile now pushed to Gemcutter</title>
   <link href="http://blog.josh-nesbitt.net/2010/02/16/lockfile-now-pushed-to-gemcutter/"/>
   <updated>2010-02-16T00:00:00+00:00</updated>
   <id>http://blog.josh-nesbitt.net/2010/02/16/lockfile-now-pushed-to-gemcutter</id>
   <content type="html">&lt;p&gt;A while ago I created a &lt;a href=&quot;/2009/09/08/implementing-a-simple-lockfile-system-in-ruby/&quot;&gt;simple lockfile implementation&lt;/a&gt; in Ruby. Just recently I received a pull request from &lt;a href=&quot;http://github.com/gregf&quot;&gt;Greg Fitzgerald&lt;/a&gt; who converted the project into a gem.&lt;/p&gt;
&lt;p&gt;Wanting to have a quick play with &lt;a href=&quot;http://gemcutter.org/&quot;&gt;Gemcutter&lt;/a&gt; I decided to build and push the gem for others to use. I have to say, &lt;a href=&quot;http://twitter.com/joshnesbitt/status/9205499123&quot;&gt;Gemcutter is slick&lt;/a&gt;. I had the gem pushed and available within a minute. Now its just a simple case of:&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;brush: plain;&quot;&gt;
  gem install simple_lockfile
&lt;/pre&gt;
&lt;p&gt;I also took the time to add some quick specs and a bit more information to the &lt;a href=&quot;http://github.com/joshnesbitt/lockfile/blob/master/readme.rdoc&quot;&gt;readme&lt;/a&gt; (where you can find usage examples). I find myself using it here and there for the odd task, so let&amp;#8217;s hope someone else finds it useful too.&lt;/p&gt;</content>
 </entry>
 
 <entry>
   <title>Writing contingent Ruby code with &#35;retryable</title>
   <link href="http://blog.josh-nesbitt.net/2010/02/08/writing-contingent-ruby-code-with-retryable/"/>
   <updated>2010-02-08T00:00:00+00:00</updated>
   <id>http://blog.josh-nesbitt.net/2010/02/08/writing-contingent-ruby-code-with-retryable</id>
   <content type="html">&lt;p&gt;Sometimes when writing a pivotal piece of code that&amp;#8217;s prone to raising errors, you want to be able to rescue and recover easily. I needed just that when I was programming some code that needed to be reliable when communicating through sockets.&lt;/p&gt;
&lt;p&gt;I found this &lt;a href=&quot;http://blog.codefront.net/2008/01/14/retrying-code-blocks-in-ruby-on-exceptions-whatever/&quot;&gt;really useful post&lt;/a&gt; on creating a &lt;em&gt;retryable&lt;/em&gt; block of code. I decided to better it by adding the ability to use multiple exception classes. Here&amp;#8217;s a really nice way of retrying a chunk of code &lt;em&gt;n&lt;/em&gt; times:&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;brush: ruby;&quot;&gt;
  def retryable(options={}, &amp;amp;block)
    attempts          = options[:attempts] || 1
    exception_classes = [*options[:on] || StandardError]
  
    begin
      return yield
    rescue *exception_classes
      retry if (attempts -= 1) &amp;gt; 0
    end
  
    yield
  end
&lt;/pre&gt;
&lt;p&gt;Use it like this:&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;brush: ruby;&quot;&gt;
  retryable(:on =&amp;gt; [MyExceptionClass, StandardError], :attempts =&amp;gt; 5) do
    # .. my risky code ..
  end
&lt;/pre&gt;
&lt;p&gt;This is great but it didn&amp;#8217;t feel as elegant as it could have been. I then stumbled across &lt;a href=&quot;http://refactormycode.com/codes/1065-retry&quot;&gt;this post&lt;/a&gt; which presented the style I was looking for. Refactored, the above snippet now looks like this:&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;brush: ruby;&quot;&gt;
  class Integer
    def tries(options={}, &amp;amp;block)
      attempts          = self
      exception_classes = [*options[:on] || StandardError]

      begin
        return yield
      rescue *exception_classes
        retry if (attempts -= 1) &amp;gt; 0
      end

      yield
    end
  end
&lt;/pre&gt;
&lt;p&gt;Which provides a cleaner call to the previous method:&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;brush: ruby;&quot;&gt;
  3.tries :on =&amp;gt; NoMethodError do
    # ... my risky code ...
  end
&lt;/pre&gt;
&lt;p&gt;This provided me a really clean way of catching socket timeout errors and service unavailable calls without repeated &lt;code&gt;begin rescue&lt;/code&gt; blocks. Of course you should always provide an error class to rescue from as rescuing from &lt;code&gt;StandardError&lt;/code&gt; will just catch any old error.&lt;/p&gt;</content>
 </entry>
 
 <entry>
   <title>The state of the internet</title>
   <link href="http://blog.josh-nesbitt.net/2010/02/06/the-state-of-the-internet/"/>
   <updated>2010-02-06T00:00:00+00:00</updated>
   <id>http://blog.josh-nesbitt.net/2010/02/06/the-state-of-the-internet</id>
   <content type="html">&lt;p&gt;&lt;a href=&quot;http://mashable.com&quot;&gt;Mashable&lt;/a&gt; recently published &lt;a href=&quot;http://mashable.com/2010/02/02/state-of-the-internet-image/&quot;&gt;an article&lt;/a&gt; about current usage statistics on the internet. The study was drawn up by &lt;a href=&quot;http://www.focus.com&quot;&gt;focus.com&lt;/a&gt; and accompanied by a really nice graphic (below).&lt;/p&gt;
&lt;p&gt;What i find most interesting is the share of people who use the internet over the share of people who are actively blogging. The most active bloggers are found in the 35-44 age range, however the 55-64 age range are more active than 18-24 year olds. On the other hand the amount of younger people using the internet is a lot larger than older age groups.&lt;/p&gt;
&lt;p&gt;I&amp;#8217;m wondering, what&amp;#8217;s it going to take for more people from younger generations to start blogging? Is there something so unappealing about signing up and creating a blog? Services such as &lt;a href=&quot;https://www.blogger.com/start&quot;&gt;Blogger&lt;/a&gt; and &lt;a href=&quot;http://www.tumblr.com/&quot;&gt;Tumblr&lt;/a&gt; have made the barriers to entry as low as possible, some would even say &lt;em&gt;inviting&lt;/em&gt;.&lt;/p&gt;
&lt;p&gt;Maybe it&amp;#8217;s the fact that you can&amp;#8217;t hide your opinions behind a blanket of other comments under the security of the latest and greatest social network. People enjoy that security, it could be that people are scared to display their opinion outside of their own friendship circles, as blogging is considerably more public and open to criticism.&lt;/p&gt;
&lt;p&gt;Maybe it&amp;#8217;s none of that. It could just be that the amount of people blogging about business, hobbies and the like are just a bit more into the whole blogging notion, as it will inevitably be more beneficial to their career or business. It&amp;#8217;ll be interesting to know if in a years time these figures still sing the same song that&amp;#8217;s for sure.&lt;/p&gt;
&lt;div style=&quot;text-align:center&quot;&gt;
&lt;img src=&quot;/assets/the_state_of_the_internet.jpg&quot; title=&quot;The state of the internet - credits: focus.com&quot; alt=&quot;The state of the internet - credits: focus.com&quot; /&gt;
&lt;/div&gt;
&lt;p&gt;Credits for the crisp graphic go to &lt;a href=&quot;http://www.focus.com&quot;&gt;focus.com&lt;/a&gt;.&lt;/p&gt;</content>
 </entry>
 
 <entry>
   <title>Managing CRON jobs the Ruby way</title>
   <link href="http://blog.josh-nesbitt.net/2009/11/30/managing-cron-jobs-the-ruby-way/"/>
   <updated>2009-11-30T00:00:00+00:00</updated>
   <id>http://blog.josh-nesbitt.net/2009/11/30/managing-cron-jobs-the-ruby-way</id>
   <content type="html">&lt;p&gt;&lt;a href=&quot;http://en.wikipedia.org/wiki/Cron&quot;&gt;&lt;span class=&quot;caps&quot;&gt;CRON&lt;/span&gt; jobs&lt;/a&gt; have always been a bit of a pain to manage. Whilst the syntax isn&amp;#8217;t the most difficult to calculate it would be nice to have an easier way to describe the intervals at which tasks should run. Even more so the schedules should be managed alongside your other project code, as one undoubtably requires the other to run (such as Rake tasks). Lots of &lt;a href=&quot;http://github.com/bokmann/crondonkulous/&quot;&gt;people&lt;/a&gt; &lt;a href=&quot;http://github.com/adzap/cronos/&quot;&gt;have&lt;/a&gt; &lt;a href=&quot;http://github.com/scrooloose/crondle/&quot;&gt;written&lt;/a&gt; &lt;a href=&quot;http://github.com/fhwang/auto_cron/&quot;&gt;gems&lt;/a&gt; &lt;a href=&quot;http://github.com/jmettraux/rufus-scheduler/&quot;&gt;and&lt;/a&gt; &lt;a href=&quot;http://github.com/javan/whenever/&quot;&gt;plugins&lt;/a&gt; to scratch this itch, one of them being &lt;a href=&quot;http://github.com/javan/whenever/&quot;&gt;whenever&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;Whenever provides a really tidy &lt;span class=&quot;caps&quot;&gt;DSL&lt;/span&gt; to declare your &lt;span class=&quot;caps&quot;&gt;CRON&lt;/span&gt; jobs in natural Ruby syntax. A basic example looks like this:&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;brush: ruby;&quot;&gt;
  set :output, File.join(&quot;log&quot;, &quot;cron.log&quot;)
  
  every 1.day do
    rake &quot;mailer:enqueue_daily&quot;
  end
&lt;/pre&gt;
&lt;p&gt;Running the &lt;code&gt;whenever&lt;/code&gt; command from your Rails project directory then produces the desired &lt;span class=&quot;caps&quot;&gt;CRON&lt;/span&gt; syntax:&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;brush: ruby;&quot;&gt;
  # =&amp;gt; 0 0 * * * cd /path/to/app &amp;amp;&amp;amp; RAILS_ENV=production /usr/bin/env rake mailer:enqueue_daily &amp;gt;&amp;gt; log/cron.log 2&amp;gt;&amp;amp;1
&lt;/pre&gt;
&lt;p&gt;This worked really well for me however I prefer to have my environment specific configurations in separate files. Although the &lt;a href=&quot;http://wiki.github.com/javan/whenever/setting-variables-on-the-fly&quot;&gt;wiki&lt;/a&gt; provided a way to do this it didn&amp;#8217;t feel very clean. A simple fix to this would be to load an environment specific file if it exists:&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;brush: ruby;&quot;&gt;
  set :output,   File.join(&quot;log&quot;, &quot;#{@environment}_cron.log&quot;)
  set :env_file, File.join(&quot;config&quot;, &quot;schedule&quot;, &quot;#{@environment}.rb&quot;)

  # Global jobs
  every 1.day do
     rake &quot;mailer:enqueue_daily&quot;
  end

  # Load environment specific jobs
  load(@env_file) if File.exists?(@env_file)
&lt;/pre&gt;
&lt;p&gt;Therefore running &lt;code&gt;whenever --set environment=staging&lt;/code&gt; would load &lt;code&gt;RAILS_ROOT/config/schedule/staging.rb&lt;/code&gt; with your staging environment specific jobs and output the result to &lt;code&gt;log/staging_cron.log&lt;/code&gt;. You can also easily integrate this into a Capistrano task when you deploy new code:&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;brush: ruby;&quot;&gt;
  desc &quot;Update the crontab file from the rules within config/schedule.rb&quot;
  task :update_crontab, :roles =&amp;gt; :db do
    run &quot;cd #{release_path} &amp;amp;&amp;amp; whenever --update-crontab #{application} --set environment=#{rails_env}&quot;
  end
&lt;/pre&gt;
&lt;p&gt;It&amp;#8217;s tools like these that make maintaining larger applications that little bit easier.&lt;/p&gt;</content>
 </entry>
 
 <entry>
   <title>Go Configure...</title>
   <link href="http://blog.josh-nesbitt.net/2009/11/11/go-configure/"/>
   <updated>2009-11-11T00:00:00+00:00</updated>
   <id>http://blog.josh-nesbitt.net/2009/11/11/go-configure</id>
   <content type="html">&lt;p&gt;Its handy to keep common configuration values inside a single file. This is nothing new and people have been doing something like this in Rails apps for quite some time:&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;brush: ruby;&quot;&gt;
  CONFIG = YAML.load_file(RAILS_ROOT + &quot;config/settings.yml&quot;)
&lt;/pre&gt;
&lt;p&gt;Whilst this is perfectly fine its not the nicest to use across your app. To me it doesn&amp;#8217;t look very pretty when accessing the values.&lt;/p&gt;
&lt;p&gt;Given the following &lt;span class=&quot;caps&quot;&gt;YAML&lt;/span&gt; file:&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;brush: ruby;&quot;&gt;
  meta:
    keywords: &quot;my, app, keywords&quot;
    description: &quot;My apps description.&quot;
&lt;/pre&gt;
&lt;p&gt;Accessing these values using the above method would look like this:&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;brush: ruby;&quot;&gt;
  CONFIG[&quot;meta&quot;][&quot;description&quot;]
&lt;/pre&gt;
&lt;p&gt;I wanted to scratch this itch, so I made a quick and dirty plugin to solve the issue. I wanted to be able to access the values easier and have them available within all of my models, mailers, views and controllers. I also wanted the plugin to auto load once dropped into a Rails project.&lt;/p&gt;
&lt;p&gt;To make things even easier I also wanted a Rake task to copy the &lt;span class=&quot;caps&quot;&gt;YAML&lt;/span&gt; files into the &lt;code&gt;config/&lt;/code&gt; directory. Although this is a trivial job, this would help to automate the installation process when using &lt;a href=&quot;http://railscasts.com/episodes/148-app-templates-in-rails-2-3&quot;&gt;Rails templates&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;Using the plugin is simple. Once installed, enter some configuration values into a &lt;span class=&quot;caps&quot;&gt;YAML&lt;/span&gt; file as normal. Then access the values from within this file within your app like this:&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;brush: ruby;&quot;&gt;
  c(:meta, :keywords)
&lt;/pre&gt;
&lt;p&gt;The plugin will try to load &lt;code&gt;config/environment.yml&lt;/code&gt; and &lt;code&gt;config/environments/RAILS_ENV.yml&lt;/code&gt; if they exist. To install these files automatically simply enter &lt;code&gt;rake configurable:install&lt;/code&gt; to copy over the default files:&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;brush: ruby;&quot;&gt;
  &amp;gt;&amp;gt; Added configuration files:
  + config/environment.yml
  + config/environments/development.yml
  + config/environments/staging.yml
  + config/environments/production.yml
&lt;/pre&gt;
&lt;p&gt;If you want to extend the plugin to be accessible in other areas of your application, you can add another hook into the &lt;code&gt;self.setup&lt;/code&gt; method located in &lt;code&gt;lib/configurable/configuration.rb&lt;/code&gt;:&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;brush: ruby;&quot;&gt;
  # lib/configurable/configuration.rb
  
  def self.setup(files)
    # ... code omitted
    
    # Add any other classes you may want the plugin to be available in below:
    MyClass::Base.send :include, Helpers
  end
&lt;/pre&gt;
&lt;p&gt;The codes nothing impressive and its a tiny plugin but its one of those things thats been annoying me for a while.&lt;/p&gt;
&lt;p&gt;Get the code:&lt;/p&gt;
&lt;ul&gt;
	&lt;li&gt;&amp;raquo; Directly from &lt;span class=&quot;caps&quot;&gt;GIT&lt;/span&gt; &lt;code&gt;git://github.com/joshnesbitt/configurable.git&lt;/code&gt;.
	&lt;ul&gt;
		&lt;li&gt;&amp;raquo; From the Github repository &lt;a href=&quot;http://github.com/joshnesbitt/configurable&quot;&gt;http://github.com/joshnesbitt/configurable&lt;/a&gt;.&lt;/li&gt;
	&lt;/ul&gt;&lt;/li&gt;
&lt;/ul&gt;</content>
 </entry>
 
 <entry>
   <title>Creating simple unique tokens in Ruby with Hasher</title>
   <link href="http://blog.josh-nesbitt.net/2009/10/12/creating-simple-unique-tokens-in-ruby-with-hasher/"/>
   <updated>2009-10-12T00:00:00+01:00</updated>
   <id>http://blog.josh-nesbitt.net/2009/10/12/creating-simple-unique-tokens-in-ruby-with-hasher</id>
   <content type="html">&lt;p&gt;Randomly hashed tokens have thousands of uses. One of them is creating a random secure hash as a handle on a user account:&lt;/p&gt;
&lt;blockquote&gt;
http://awesomewebapp.com/confirm/843e9d74d716b41517addde515f4e6db940be21d
&lt;/blockquote&gt;
&lt;p&gt;A random unique hash is created and assigned to your account, allowing you to confirm your identity through a link without disclosing any personal information about who you are. Hashes like this can easily be created by digesting a single string or a string with an additional salt injected into it to ensure the original string is even more indecipherable.&lt;/p&gt;
&lt;p&gt;I was seeing quite a lot of duplication in areas of my code where I was constructing hashes based on certain attributes of a particular class. This required me to build up a hash-able string and then pass it through SHA1 to digest it. Although this is only a few lines of code, its nice to bundle this up into a reusable module so you can just do something like this:&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;brush: ruby;&quot;&gt;
  generate_hash &quot;somevalueiwanttohash&quot; # =&amp;gt; 1a09a8b3dd4b24d5284ac13705523d1b15b55e64
&lt;/pre&gt;
&lt;p&gt;Thats where &lt;a href=&quot;http://github.com/joshnesbitt/hasher&quot;&gt;Hasher&lt;/a&gt; comes in, a simple module you can mix into any Ruby project. Heres the code:&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;brush: ruby;&quot;&gt;
  # hasher.rb
  # git://github.com/joshnesbitt/hasher.git
  
  module Hasher
    require 'digest/sha1'
    SECRET = &quot;ilikebigbuttsandicannotlie&quot;

    def generate_hash(string)
      encrypt string
    end

    protected
    def encrypt(string)
      Digest::SHA1.hexdigest(salt + string)
    end

    def salt
      Digest::SHA1.hexdigest(SECRET + time_stamp + random)
    end

    def time_stamp(time = Time.now)
      time.strftime(&quot;%d%Y%l%M&quot;).to_s
    end

    def random(size = 10)
      (0...size).map { character_set[ rand(character_set.size) ] }.join
    end

    def character_set
      [('0'..'9'),('A'..'Z')].map { |range| range.to_a }.flatten
    end
  end
&lt;/pre&gt;
&lt;p&gt;So say you want to create a confirmation token for a user &lt;code&gt;before_create&lt;/code&gt;, you would use it in an &lt;a href=&quot;http://api.rubyonrails.org/classes/ActiveRecord/Base.html&quot;&gt;ActiveRecord&lt;/a&gt; model like this:&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;brush: ruby;&quot;&gt;
  # app/models/user.rb
  
  class User &amp;lt; ActiveRecord::Base
    include Hasher
    
    # ... other ruby code ...
    
    before_create :generate_confirmation_token
    
    protected
    def generate_confirmation_token
      self.confirmation_token = generate_hash(&quot;#{self.id}-#{self.email}&quot;)
    end
  
  end
&lt;/pre&gt;
&lt;p&gt;Its not much, but if you end up having more models needing similar functionality it makes sense to package it up into a nice mixin.&lt;/p&gt;</content>
 </entry>
 
 <entry>
   <title>Using ActionMailer layouts with Clearance</title>
   <link href="http://blog.josh-nesbitt.net/2009/09/11/using-actionmailer-layouts-with-clearance/"/>
   <updated>2009-09-11T00:00:00+01:00</updated>
   <id>http://blog.josh-nesbitt.net/2009/09/11/using-actionmailer-layouts-with-clearance</id>
   <content type="html">&lt;p&gt;If you&amp;#8217;re building a Rails application thats going to be sending a lot of emails, chances are you&amp;#8217;re going to want to have a consistent layout between each. You use layouts within your application so why not use them in your mailers? Since commit &lt;a href=&quot;http://github.com/rails/rails/commit/e9a8e0053be3b293ab89fb584f1d660063f107aa&quot;&gt;e9a8e0053be3b293ab89fb584f1d660063f107aa&lt;/a&gt; you&amp;#8217;ve been able to use layouts within your mailers, making it easy to implement a consistent email format across all emails.&lt;/p&gt;
&lt;p&gt;You use them just like normal rails layouts, i tend to explicitly declare the mailer layout at the top of my mailer class. More specifically i usually declare a base mailer class to use as the parent class for all my other mailers, making setting up and configuring each mailer really easy, heres what mine looks like:&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;brush: ruby;&quot;&gt;
# app/models/base_mailer.rb

class BaseMailer &amp;lt; ActionMailer::Base
  layout &quot;mailer&quot;
  default_url_options[:host] = HOST # set in development/staging/production.rb

  protected
  def setup_mail(email)
    from          DO_NOT_REPLY # set in development/staging/production.rb
    recipients    email
    subject      &quot;[My Mailer] &quot;
    sent_on       Time.now
  end

end
&lt;/pre&gt;
&lt;p&gt;Then my object specific mailer:&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;brush: ruby;&quot;&gt;
# app/models/enquiry_mailer.rb

class EnquiryMailer &amp;lt; BaseMailer

  def after_create(enquiry)
    setup_mail(enquiry.email)
    @subject += &quot;Thanks for contacting us.&quot;
    @body = { :name =&amp;gt; enquiry.name }
  end

end
&lt;/pre&gt;
&lt;p&gt;I, like a lot of people use &lt;a href=&quot;http://www.thoughtbot.com/projects/clearance&quot;&gt;Clearance&lt;/a&gt;, an authentication engine written by the guys from &lt;a href=&quot;http://www.thoughtbot.com&quot;&gt;Thoughtbot&lt;/a&gt;. Obviously you want to take advantage of the same mailer layouts within the Clearance mailers too, so lets tweak the &lt;code&gt;ClearanceMailer&lt;/code&gt; class to tell it about the layout:&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;brush: ruby;&quot;&gt;
# config/initializers/apply_clearance_mailer_layout.rb

ClearanceMailer.class_eval { layout &quot;mailer&quot; }
&lt;/pre&gt;
&lt;p&gt;This performs a &lt;a href=&quot;http://www.ruby-doc.org/core/classes/Module.html#M001650&quot;&gt;class_eval&lt;/a&gt;, modifying the class when the application initialises to use the mailer layout we&amp;#8217;re using in the rest of our application. If you&amp;#8217;re sending a lot of mails it pays off to keep them all consistent, as sometimes this is the first port of call for your client/customer.&lt;/p&gt;</content>
 </entry>
 
 <entry>
   <title>Implementing a simple lock file system in Ruby</title>
   <link href="http://blog.josh-nesbitt.net/2009/09/08/implementing-a-simple-lockfile-system-in-ruby/"/>
   <updated>2009-09-08T00:00:00+01:00</updated>
   <id>http://blog.josh-nesbitt.net/2009/09/08/implementing-a-simple-lockfile-system-in-ruby</id>
   <content type="html">&lt;p&gt;&lt;a href=&quot;http://en.wikipedia.org/wiki/Lock_file#Lock_files&quot;&gt;Lock Files&lt;/a&gt; are great for monitoring when a resource is in use, &lt;a href=&quot;http://en.wikipedia.org&quot;&gt;Wikipedia&lt;/a&gt; explains it simply:&lt;/p&gt;
&lt;blockquote&gt;
File locking is often used by shell scripts and other programs: creation of lock files, which are files whose contents are irrelevant (although often one will find the Process identifier of the holder of the lock in the file) and whose only purpose is to signal by their presence that some resource is locked. A lock file is often the best approach if the resource to be controlled is not a regular file at all, so using methods for locking files does not apply.
&lt;a href=&quot;http://en.wikipedia.org/wiki/Lock_file#Lock_files&quot; class=&quot;source&quot;&gt;- Wikipedia&lt;/a&gt;
&lt;/blockquote&gt;
&lt;p&gt;Recently whilst working on a project i needed to implement some way of monitoring when a particular task was being executed, ensuring that a duplicate task wasn&amp;#8217;t invoked (consuming more resources and possibly hindering the execution of the current task). Ruby (and pretty much any other programming language) provides a whole host of file manipulation classes to easily implement a simple lock file system.&lt;/p&gt;
&lt;p&gt;With Ruby we can use the &lt;code&gt;File&lt;/code&gt; class to manipulate files, ensuring a platform independent way of reading/writing to/from the filesystem. The actual class methods that we&amp;#8217;ll be using within the &lt;code&gt;File&lt;/code&gt; class come from the mixin of the &lt;code&gt;ftools&lt;/code&gt; module (which adds a group of methods for copying, moving, deleting, installing, and comparing files).&lt;/p&gt;
&lt;p&gt;Heres the code:&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;brush: ruby;&quot;&gt;
# lock_file.rb
# git://github.com/joshnesbitt/lockfile.git

class LockFile
  attr_accessor :path, :filename, :qualified_path

  def initialize(path=&quot;/tmp&quot;, filename=&quot;lockfile.lock&quot;)
    @path, @filename = path, filename
  end

  def path
    @path
  end

  def filename
    @filename
  end

  def qualified_path
    &quot;#{@path}/#{@filename}&quot;
  end

  def process_id
    locked? ? read_lockfile(self.qualified_path) : nil
  end

  def lock!
    locked? ? false : create_lockfile(self.qualified_path)
  end

  def unlock!
    unlocked? ? false : destroy_lockfile(self.qualified_path)
  end

  def locked?
    lockfile_exists?(self.qualified_path)
  end

  def unlocked?
    !lockfile_exists?(self.qualified_path)
  end

  protected
  def lockfile_exists?(file)
    File.exists?(file)
  end

  def create_lockfile(lockfile)
    begin
      File.open(lockfile, &quot;w&quot;) { |f| f.write(Process.pid) }
    rescue
      raise LockFileExists
    end
  end

  def read_lockfile(lockfile)
    begin
      File.open(lockfile, &quot;r&quot;).gets { |l| puts l }
    rescue
      raise LockFileMissing
    end
  end

  def destroy_lockfile(lockfile)
    begin
      File.delete(lockfile)
    rescue
      raise LockFileMissing
    end
  end

  class FileError &amp;lt; StandardError #:nodoc:
  end
  class LockFileExists &amp;lt; FileError #:nodoc:
  end
  class LockFileMissing &amp;lt; FileError #:nodoc:
  end  

end
&lt;/pre&gt;
&lt;p&gt;This is a very basic implementation as i didn&amp;#8217;t need anything uber fancy. Use it like this:&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;brush: ruby;&quot;&gt;
l = LockFile.new(&quot;/path/to/lockfile&quot;, &quot;test.lock&quot;)
# =&amp;gt; &quot;/path/to/lockfile/test.lock&quot; containing the PID

l.locked?
# =&amp;gt; false

l.lock!
# =&amp;gt; Integer value

l.locked?
# =&amp;gt; true

l.process_id
# =&amp;gt; PID

l.unlock!
# =&amp;gt; Integer value

l.locked?
# =&amp;gt; false
&lt;/pre&gt;
&lt;p&gt;To put it into context a bit more, imagine you&amp;#8217;re doing something like this within your application:&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;brush: ruby;&quot;&gt;
def do_something
    call_rake_task
end
&lt;/pre&gt;
&lt;p&gt;When hit this method will call a Rake task from within your application, lets not worry about why you might be doing this for now but focus on how we ensure this task isn&amp;#8217;t invoked again if it&amp;#8217;s already being executed:&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;brush: ruby;&quot;&gt;
def do_something
    call_rake_task unless @lockfile.locked?
end
&lt;/pre&gt;
&lt;p&gt;Where you initialize the lock file instance is up to you, i ended up creating it in the initializer of the class i was using it in to make sure it was available as soon as the class was instantiated.&lt;/p&gt;
&lt;p&gt;There are lots of uses for lock files, for me this was just one quick solution to a problem. Also its important to note that there are other solutions to performing expensive tasks outside of a typical request (most of which are better than using plain old lock files), you might want to look at these too:&lt;/p&gt;
&lt;ul&gt;
	&lt;li&gt;&lt;a href=&quot;http://github.com/tobi/delayed_job/tree/master&quot;&gt;Delayed Job&lt;/a&gt;&lt;/li&gt;
	&lt;li&gt;&lt;a href=&quot;http://railscasts.com/episodes/129-custom-daemon&quot;&gt;Custom Daemon&lt;/a&gt;&lt;/li&gt;
	&lt;li&gt;&lt;a href=&quot;http://railscasts.com/episodes/128-starling-and-workling&quot;&gt;Starling &amp;amp; Workling&lt;/a&gt;&lt;/li&gt;
	&lt;li&gt;&lt;a href=&quot;http://railscasts.com/episodes/127-rake-in-background&quot;&gt;Background Rake&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Bonza!&lt;/p&gt;</content>
 </entry>
 
 <entry>
   <title>Deployment tip when using Passenger and Capistrano</title>
   <link href="http://blog.josh-nesbitt.net/2009/09/06/deployment-tip-when-using-passenger-and-capistrano/"/>
   <updated>2009-09-06T00:00:00+01:00</updated>
   <id>http://blog.josh-nesbitt.net/2009/09/06/deployment-tip-when-using-passenger-and-capistrano</id>
   <content type="html">&lt;p&gt;A quick tip i picked up from a &lt;a href=&quot;http://gist.github.com/&quot;&gt;Gist&lt;/a&gt; off &lt;a href=&quot;http://www.github.com&quot;&gt;Github&lt;/a&gt;. Every time you deploy new changes to a rails application powered by Passenger using Capistrano, chances are you&amp;#8217;re going to be restarting the application by hitting &lt;code&gt;tmp/restart.txt&lt;/code&gt;. The first time you access the site after every restart you&amp;#8217;ll experience a short hang whilst the passenger process spawns. A good way to stop this is by pinging the applications &lt;span class=&quot;caps&quot;&gt;URL&lt;/span&gt; after you&amp;#8217;ve touched the restart file:&lt;/p&gt;
&lt;pre name=&quot;code&quot; class=&quot;brush: ruby;&quot;&gt;
desc &quot;Restarts this application when running passenger&quot;
task :restart, :roles =&amp;gt; :app do
  run &quot;touch #{current_path}/tmp/restart.txt&quot; 
  `curl -s http://myhost.com $2 &amp;gt; /dev/null`
end
&lt;/pre&gt;
&lt;p&gt;This hits the &lt;span class=&quot;caps&quot;&gt;URL&lt;/span&gt; specified and throws the output to &lt;code&gt;/dev/null&lt;/code&gt;. It might seem like nothing but if it saves you 10 seconds on every deploy it can&amp;#8217;t be a bad thing&amp;#8230;&lt;/p&gt;</content>
 </entry>
  
</feed>
