• Some Rails Tips and Tricks

    After doing a lot of refactoring today I wanted to note a few useful things I’ve picked up.

    load the rails environment for rake

    If you need to run a rake task that need access to the Rails models, etc. add the :environment dependency

    task :my_task => :environment do 

    Testing Delayed Job

    Added the following to tell Delayed Job to run without delays.

    Delayed::Worker.delay_jobs = false

    Or the following to run a last Job and check for Success and Fail, in the returned array.

    Delayed::Worker.new.work_off.should == [1, 0]

    Check the Job Count with one of the following

    Delayed::Job.count.should == 1
    # OR
    lambda do
      # code the should schedule a delayed job
    end.to change(Delayed::Job.count).by(1)

    ActiveRecord add_column and update

    In a migration, sometimes you want to add a new column, then update it do a new value.

    def self.up
      add_column :users, :plan_id, :integer
      User.update_all("plan_id = 1")

    FactoryGirl Callbacks

    When setting up complex relationships with FactoryGirl, callbacks can help.

    FactoryGirl Callbacks

    Factory.define :user do |user|
      user.name "Dusty Candland"
      user.email "testing@testing.com"
      user.phone "303-333-3333"
      user.password "foobar"
      user.password_confirmation "foobar"
    Factory.define :user_with_subscription, :parent => :user do |user|
      user.after_create{|u| Factory(:user_subscription, :user => u)}
    Factory.define :user_subscription do |sub|
      sub.first_name 'beta'
      sub.last_name 'test'
      sub.number '4111111111111111'
      sub.expiration_year 2012
      sub.expiration_month 1
      sub.zip_code '90210'
      sub.price 2.50
      sub.group_limit 1
      sub.message_limit 100
      sub.association :plan
      sub.user_id 1
  • Rails AJAX Posts Session Reset

    Notes regarding AJAX post requests being logged out on Rails. Seems the problem is not adding the CSRF data.

    The problem was that AJAX post requests resulted in a redirect to the login page. Further inspection showed the cookie was being passed, but the session on server was empty. Rails wasn’t getting the correct CSRF value and as a result, resetting the session data.

    This StackOverflow post has some useful info Rails not reloading session on ajax post.

    This lead to a post by Jason Weathered CSRF vulnerability in Ruby on Rails 2.3.10 & 3.0.3.

    Which ended up at the jQuery UJS project. Installing this fixed the problem!

  • Moving My Blog to the Toto Ruby Blog

    I’ve decided to switch this blog off wordpress and go w/ something closer to the metal. Toto is a rack based blogging engine that uses markdown and basic test files. This is a good approach because you get complete control, but also an editing environment that’s close to normal coding. Heres some links that helped me get up and running.

    Getting Started With toto

    XmlRPC UTF-8 Fix

    Blogging With Toto

    require 'rubygems'
    require 'fastercsv'
    require 'xmlrpc/client'
    USERID = '<userid>'
    PASSWORD = '<password>'
    # http://www.eggheadcafe.com/microsoft/Ruby/36270580/xmlrpc-rexml-incorrectly-handles-utf8-data.aspx
    # http://tedwise.com/2010/05/25/blogging-with-toto/
    module XMLRPCWorkAround
        def do_rpc(request, async=false)
            data = super
    def getPages(blog)
      blog.call("wp.getPages", 0, USERID, PASSWORD, 1000)
    def getPosts(blog)
      blog.call("metaWeblog.getRecentPosts", 0, USERID, PASSWORD, 1000)
    def slugify(title)
      title.downcase.gsub(/[ \._]/, '-')
    blog = XMLRPC::Client.new3(:host => "<your-wordpress-blog.com>", :path => "/xmlrpc.php")
      puts "Logging into blog and getting the list of posts..."
      posts = getPosts(blog)
      puts "  response received, found #{posts.size} posts"
      `mkdir articles`
      posts.each do |post|
        permaLink = post['permaLink']
            puts permaLink
        dateAndName = permaLink.gsub(/http:\/\/your-wordpress-blog\.com\//, '').split('/')
        postFilename = 'articles/' + dateAndName.join('-') + '.txt'
        postDate = dateAndName[0] + '/' + dateAndName[1] + '/' + dateAndName[2]
        escapedTitle = post['title'].gsub(/"/, '\\"')
        File.open(postFilename, "w") do |postFile|
          postFile.puts("title: \"#{escapedTitle}\"")
          postFile.puts("author: dusty candland")
          postFile.puts("date: #{postDate}")
          postFile.puts("slug: #{dateAndName[3]}")
          puts "#{post['title']} - #{postDate}"
          postFile.puts("categories: #{post['categories']}")
          postFile.puts("keywords: #{post['mt_keywords']}")
          postFile.puts post['description']
    rescue XMLRPC::FaultException => e
       puts "ERROR: Code: #{e.faultCode}"
       puts "ERROR: Msg.: #{e.faultString}"
  • Rails No Data Model

    Take advantage of ActiveModel without a database backend.

    class NoDataModel
      include ActiveModel::Validations
      include ActiveModel::Conversion
      extend ActiveModel::Naming
      def initialize(attributes = {})
        attributes.each do |name, value|
          send("#{name}=", value) if respond_to? "#{name}="
      def persisted?
  • Notes On Capistrano to Windows 2008


    install openssh via cygwin, include vim and git.

    setup git in cygwin not windows

    if git for windows is installed, do not include use the git unix commands (remove from PATH if you installed that way)

    Change the .bashrc file to prepend /usr/local/bin:/usr/bin to path

    export PATH=/usr/local/bin:/usr/bin:$PATH

    If not running interactively, don’t do anything

    [[ “$–” != i ]] && return

    debug path issues

    cap shell

    cap> echo $PATH



  • Savon.rb client for .Net web service.

    This is a quick post to help anyone looking for info on consuming a dotNet based webservice using the savon gem for ruby. The main issue is that .net expects a namespace on the action element in the soap body. This can be done easily in the call to client#request as shown in the following gist. Hope this saves someone, maybe future me, some time!

  • No, I can’t build Facebook for $500!

    I’ve been freelancing full time for over a year now and have found that finding and bidding for new work takes a ton of time! The perception of what something should cost has moved far for reality. I’m wondering if other freelancers have run into this problem?

    I have some ideas to help alleviate some of the problems related to freelancing, if you’re interested in any way, please contact me.