Warning: Creating default object from empty value in /homepages/39/d161420129/htdocs/p373.net/wp/wp-content/themes/p373b/admin/functions.php on line 183
P373 | Global Technology, Activism, Philosophy, Photography.

Stub a ruby method and conditionally raise an exception based upon state of object

(If you want to skip my fancy and hilarious writing, skip straight to the SO post)

Here’s the use case:

You’re building  a mass email system for your globo-mega-corp’s 90,000 employees.  Your corp’s smtp server can only handle batches of 450 recipients at a time.  Your boss tells you your corp’s SMTP server is finicky and rejects batches from time to time for no apparent reason.  She also dictates that if one batch fails the rest must succeed and you must keep track of which recipients received the email and which did not so that you can resend the batches that failed.  Easy enough, you think, we’re using Ruby on Rails.  And you write something like the following code:

def send_batches(batches)
  batches.each do |batch|
    begin
      batch.deliver!
    rescue Exception => e
      batch.update_attributes(failed_at: Time.now, failure: e.message)
    end
  end

  if batches.failed.length > 0
    ExceptionNotifier.send("Some batches failed")
  else
    batches.destory_all
  end
end

Its not the best code, but you’re under deadline because the CEO of GloboMegaCorp wants to invite everyone over to his mansion for daiquiris this weekend.   So now, like the good little developer you are, you write your test code(actually, you wrote your test code first, didn’t you??).

 

it "sends multiple batches gracefully when one fails in the middle" do

  mm = MassMailer.new(subject: "Daiquiris, Lets do it!", from: "Don Juan The Ceo", to: "GloboMegaCorp Staff List", body: "My house on Sat, bring your speed-o!")
  mm.send_batches(Staff.all.each_slice(450).to_a)

end

Did you hear the record scratch in your brain?  How are you going to test that your exception handling code works?  You need to trigger an exception on one of the batches but let the rest proceed as normal….hmmm….do you hear the Jeopardy music playing?? Times up!

Here’s how we can make one object that we don’t have control over throw an exception in our test:

Mail::Message.any_instance.stub(:deliver) do |message|
  raise Exception, "oh no you di'nt" if message.bcc and message.bcc.include?("vanna.white@globomegacorp.com")
  ActionMailer::Base.deliveries << message
end

So what I’ve done here is stubbed out the deliver call on any instance of Mail::Message and I throw an exception at my discretion.  In this case, I throw an exception on the batch that Vanna is in.  I also make sure to add in the message to the deliveries array so I can test actual deliveries, particularly the delivery of the exception notification.  Otherwise, mails do not get “sent” because we’ve stubbed out the “deliver” method, remember?

Now, dear reader, you might have skipped straight to the code and tried it out, and screamed some profanities at your dear author that this code is buggy.  Well, perhaps you should keep reading then and not be so hasty, ey?

This code will work for Rspec version 3.  What’s that?  You’re still on v2?  Oh, well so am I.  I even tried upgrading, but that was a nightmare this little old legacy app that contrived this sweet example.  So lucky for you I’ve got the tonic:

class RSpec::Mocks::MessageExpectation
  def invoke_with_orig_object(parent_stub, *args, &block)
    raise "Delete me.  I was just stubbed to pull in behavior from RSpec v3 before it was production ready to fix a bug!  But now I see you are using Rspec v3. See this commit: https://github.com/rspec/rspec-mocks/commit/ebd1cdae3eed620bd9d9ab08282581ebc2248535#diff-060466b2a68739ac2a2798a9b2e78643" if RSpec::Version::STRING > "2.99.0.pre"
    args.unshift(@method_double.object)
    invoke_without_orig_object(parent_stub, *args, &block)
  end
  alias_method_chain :invoke, :orig_object
end

Drop that bad boy at the bottom of your test and you’re good to go.  You’ll notice I was even nice enough to throw an exception to warn you when you’ve upgraded.  Because if you’re like me, I will upgrade months from now and have no recollection that I did this nifty monkey patch.

Happy days.

Posted in Coding, Ruby/Rails, Technology | Tagged , , | Comments closed

Adventures in Grunt-Land Part II: How to dynamically update files with Grunt-Replace

In the previous post, I went over how to setup Grunt so that you can have environment based builds.  A build for your development environment would have a destination of builds/development, builds for staging would go to builds/staging, and builds for production go to builds/production.  You get the idea.

In this post, let’s take our environment based configuration a step further, and actually update our Chrome extension manifest to have permissions based on the environment we’re building for.

In manifest.json we have:

    "permissions": ["http://localhost", "http://staging.mysite.com", "http://mysite.com"],

When a user goes to install our Chrome extension they will be able to see all of these things listed under the permissions the extension has access to communicate with.  We don’t like this.

Instead, we will use Grunt-Replace, to process our manifest file and update it with permissions that will place in our environment config.  Here is the code, and I’ll explain what’s going on below.

// manifest.json
"permissions": @@PERMISSIONS

// Gruntfile.js
grunt.initConfig({
  replace: grunt.file.readJSON('grunt/replace.json'),
})

grunt.registerTask('build', [
        'clean:dist',
        'replace:dist',        
        'chromeManifest:dist',
        'useminPrepare',
        // 'concurrent:dist',
        'notConcurrent',
        'cssmin',
        'concat',
        'uglify',
        'copy',
        'usemin',
        'replace:clean',
        'compress'
    ]);

// grunt/replace.json
{
  "dist": {
    "options": {
      "patterns": [{
        "match": "PERMISSIONS",
        "replacement": "<%= JSON.stringify(env[BUILD_ENV].permissions)%>"
      }]
    },
    "files": [
      {
        "expand": true, 
        "flatten": true, 
        "src": ["<%= yeoman.app%>/manifest.json"],
        "dest": "<%= yeoman.app %>/"
      }
    ]
  },
  "clean": {
    "options": {
        "patterns": [{
            "match": "/permissions[\\s\\S]*?\\]/",
            "replacement": "permissions\": @@PERMISSIONS",
            "expression": true
          }
        ],
        "prefix": ""
      },
      "files": [
        {
        "expand": true, 
        "flatten": true, 
        "src": ["<%= yeoman.app%>/manifest.json"],
        "dest": "<%= yeoman.app %>/"
        }
      ]
  }
}

 

First, I would like to point out that you’ll notice I’ve abstracted the replace config into a json file.  I noticed that my Gruntfile config was getting out of controller, so I think having your grunt configs in separate files underneath a grunt/ directory is a good, clean pattern.  There is a gotcha here, make sure that you use “expression”: true, and NOT “expression”: “true”.

As well, you will notice that I have two targets: dist and clean.  The chromeManifest task does its magic by reading manifest.json in the source directory, so I need to modify manifest.json in the source directory and then once chromeManifest task is completed, we need to revert it back to its original form for future tasks.  The replace:dist task modifies the manifest.json file in place, and then replace:clean, puts it back.

And there you have it, now our Chrome extension will only have permissions specified for the appropriate build.

Posted in Coding, Ruby/Rails, Technology | Tagged , , | Comments closed

How to create environment based builds with Grunt

Grunt is pretty neat when it comes to creating builds of javascript applications.  However, I found it quite difficult to create environment based builds, ie, builds for development, staging, and production.

First off, let me say that I’m not a javascript developer.  In reality, what I”m trying to do is very simple: create a deployment pattern for a Google Chrome extension.  The idea is that I want to be able to specify environment configuration variables such as endpoint and build directory so I can point different builds to different directories and have their api clients talk to different endpoints.

Let’s start with getting a chrome extension to build to different directories depending on which Grunt build task I execute.

First, you need to install grunt-env(You should probably already have Grunt installed).  Start by following the usual instructions here: https://github.com/jsoverson/grunt-env

To be nice, I’ll be explicit as well:

// You want the --save-dev so it updates your package.json file
npm install grunt-env --save-dev

At the bottom of your Gruntfile:

grunt.loadNpmTasks('grunt-env');

In your grunt.initConfig({…}) block, enter:

  env : {
    options : {
    //Shared Options Hash
    },
    dev : {
      NODE_ENV : 'development',
      DEST     : 'builds/dev'
    },
    build : {
      NODE_ENV : 'production',
      DEST     : 'builds/production'
    }
  }

If you look at the README for the grunt-env project, you’ll notice I”ve gone away from what they have.  It baffles my mind that its the convention to have a “dist” directory at the top level of a project, as opposed to have a builds directory where you can have any number and types of builds.  So thats why I’ve put DEST: “builds/production”.

Grunt now gives us tasks to specify which environment we want, like so:

grunt.registerTask('dev', ['env:dev', 'build']);

This is all gravy, but how do you take advantage of your environment configuration variables?

This took me forever to figure out, but alas, that’s why I’m writing this blog post, and you, dear reader, are reading it :)

Ok, so there are two ways you might want to access these variables:

  1. 1. In a task
  2. 2. In a template in the configuration

1. Accessing environment configuration in a task is straightforward, as long as you combed through the source code and figured it out, or read below:

process.env.DEST

2. Accessing from within a template

You might think, you could just do:

grunt.initConfig({
  chromeManifest: {
    dist: {
      dest: '<% process.env.DEST%>'
    }
  } 
})

But you’d be wrong!  Templates are executed in the context of the configuration, so you don’t have access to process.  What you need to do, is set a configuration var inside a task that has access to process.  Here’s the special sauce:

grunt.registerTask('setenv', 'Override all grunt build options with environment specific options', function() {

grunt.config('BUILD_ENV', process.env.ENV)

});

And then in the template:

dest: '<%= env[BUILD_ENV].DEST %>'

Boom! environment based configuration for dinner. delicious.

In part 2 of adventures in Grunt-land, I’m going to go over how to update a Google Chrome extension manifest file with an environment configuration file

Posted in Coding, Ruby/Rails, Technology | Tagged , , | Comments closed

Recursively generate nested errors in json with Rails

See this gist: https://gist.github.com/synth/8511262

    def nice_errors(object, errors)
      object.errors.each do |key|
        error_obj = object.send(key)
        if error_obj.kind_of?(Array)
          errors[key] = {}
          error_obj.each {|item| nice_errors(item, errors[key])}
        elsif error_obj.kind_of?(ActiveRecord::Base)
          errors[error_obj.id] = {}
          nice_errors(error_obj, errors[error_obj.id])
        else
          errors[key] = object.errors[key]
        end
      end
      return errors
    end
  end

  # call it with
  nice_errors(resource, {})

  # will generate something like:
  {"errors":{"user_recipients":{"email":["may not be the same as your own email"]}}}
Posted in Coding, Ruby/Rails, Technology | Comments closed

An algorithm to generate fake but realistic stock price graph data that trends

Sometimes you want to generate data. Generating random data is pretty easy, but that doesn’t represent real user behavior. Real user behavior probably follows patterns. Here is an approach to generating some data that approximates stock price fluctuations.

The below algorithm will generate a string of code that can be input into Google charts for visualization here: https://code.google.com/apis/ajax/playground/?type=visualization#line_chart

    # In order to generate a semi-realistic looking graph behavior
    # we use a sine function to generate periodic behavior(ups and downs).  In order to avoid
    # a graph that is too regular, we introduce randomness at two levels:
    # The delta between steps across the x-axis is random, but within a range(deltavariance)
    # The wavelength of the sine function is varied by randomly incrementing the index we pass
    # to the sine function(sine_index)

    # CONFIGURATION VARIABLES
    yvalue = 1 # start value
    range = 100 # y-range
    deltavariance = 10 # allowable variance between changes
    sine_index, wavelength = 0, 0.33 #index into our sine function that determines whether we change direction or not
    i, maxi = 0, 100 # our counter and its maximum
    data = {sine_index => yvalue} # seed our data structure with its first value
    trend = :positive # :negative, :none # do we want the graph to trend upwards, downwards or neither
    periodmin, periodmax = 0, 0 # vars to enforce trending
    direction = 1 # start in a positive direction, -1 for negative

    # DO NOT EDIT BELOW THIS LINE
    while(i < maxi)

      olddirection = direction
      direction = Math.sin(sine_index).to_f
      direction = direction < 0 ? direction.floor : direction.ceil

      delta = rand(deltavariance) 
      yvalue += delta * direction

      if trend == :positive 
        yvalue = periodmin if yvalue < periodmin
        periodmin = yvalue if olddirection < direction
      elsif trend == :negative
        yvalue = periodmax if yvalue > periodmax
        periodmax = yvalue if olddirection > direction

      end

      data[sine_index] = yvalue
      sine_index += Math.sin(rand) # Math.sin(rand) will give random numbers from -1..1
      i += 1
    end

    code = <<-CODE
    function drawVisualization() {
      // Create and populate the data table.
      var data = google.visualization.arrayToDataTable([
        ['x', 'Cats'],
        DATASTR
      ]);

      // Create and draw the visualization.
      new google.visualization.LineChart(document.getElementById('visualization')).
          draw(data, {curveType: "function",
                      width: 500, height: 400,
                      vAxis: {maxValue: 10}}
              );
    }
    CODE

    datastr = data.collect{|k,v|  "[#{k},#{v}]"}.join(",")
    code = code.gsub('DATASTR', datastr)
    puts code
Posted in Coding, Ruby/Rails, Technology | Comments closed

How to customize Http Digest Authentication error pages in Ruby on Rails

Say you are working on a site that has a splash/landing page that is public, but the site rest of the site needs to be locked down to a small group of people to alpha test. You could build this into your authentication model, or you could do it quickly and easily using HTTP Digest Authentication.

Setting up Digest authentication is beyond the scope here, so I”ll refer you to: The API

Once that’s set up, its straight forward to use, but if a user tries to access a page and doesn’t have the correct credentials and they click cancel they will be redirected to an empty white page with the abrasive words: “HTTP Digest: Access denied.\n”

Its easy to send them to your 401.html living in public. You did create one didn’t you? Neither did I, but I just copied 404.html and replaced some of the text easy-peazy.

This customization relies on a monkey patch(or is it Freedom Patching).

 

module ActionController
  module HttpAuthentication
    module Digest
      def authentication_request_with_customization(controller, realm, message=nil)
        message = controller.render_to_string("public/401.html")
        authentication_request_without_customization(controller, realm, message)
      end
      alias_method_chain :authentication_request, :customization
    end
  end
end
Posted in Coding, Ruby/Rails, Technology | Comments closed

Carrierwave custom validations

The use case here is when you need to conditionally validate the extensions you validate.  In our case, we only wanted to validate the extension white list when a local file was uploaded.  This is because our users can signup via Yammer during which we suck in their mugshot images.  Yammer’s mugshot urls do not have extensions so we need to bypass the whitelist validation during this process.

This is easy enough using Carrierwave’s validates_integrity_of method.

class AvatarAttachment < ActiveRecord::Base
  mount_uploader :file, AvatarAttachmentUploader
  belongs_to :user
  validates_integrity_of :file, if: :should_validate_file
 
  protected
  def should_validate_file
    return (self.changes[:file] and self.file.present?) 
  end  
end

We just check if there is a file present; in the case of remote file urls, file is nil and remote_file_url is populated.

Simple and powerful.  Just the way I like it.

Posted in Coding, Ruby/Rails, Technology | Tagged , | Comments closed

Forget pretty urls, how about vain gorgeous urls

In Rails, resource based urls are by default not pretty.  For example, say you have the following routing

     resources :projects do
       resources :users
     end

This yields urls

     /projects
     /projects/1
     /projects/1/users
     /projects/1/users/1

So to make pretty urls, its pretty trivial.  Just implement #to_param on the project model and user model

     #app/models/project.rb
     class Project < ActiveRecord::Base
       …
       def to_param
         slug #selected by user
       end
     end

     #app/models/user.rb
     class User < ActiveRecord::Base
       …
       def to_param
         slug #selected by user
       end
     end

This will now yield urls as

     /projects/sony
     /projects/sony/users/mary

However, it seems silly to me always have “projects” and “users” in the url.  Can’t we just have

      /sony/mary

Of course we can.  Here’s the full code and below I’ll explain in detail below

     # routes.rb
     match "/projects" =&gt; "projects#index", as: "projects" 
     match "/users" =&gt; "users#index", as: "users" 
     resources :projects, path: "", path_names: {new: "projects/new", create: "projects/create"}, except:[:index] do
       resources :users, path: "", path_names: {new: "users/new"}, except:[:index, :create]
     end

<span style="font-family: Georgia, 'Times New Roman', 'Bitstream Charter', Times, serif; font-size: 13px; line-height: 19px;">So, the main idea here is that we change the path argument to an empty string which gets rid of "projects" and "users" from the url.  However, this presents a couple of problems with the index, new, and create actions as these are not scoped to an object and need to have the "/projects" and "/users" in the url so the request knows what controller we're talking about.  </span>

This is easily achieved by changing the “path_names” argument for the new and create actions.  For some reason, the index action needs to be listed as a separate route.  I’m not sure why but this is what I did to get it to work.

Voila, gorgeous urls.

GOTCHA: if you add extra member or collection routes or even other nested resource routes, they must be listed ABOVE the resources that will be utilized in this fashion, otherwise, that resource name will be matched as the id for a user.

     # routes.rb
     match "/projects" => "projects#index", as: "projects" 
     match "/users" => "users#index", as: "users" 
     resources :projects, path: "", path_names: {new: "projects/new", create: "projects/create"}, except:[:index] do
       resources :users, path: "", path_names: {new: "users/new"}, except:[:index, :create]
       resources :tasks #WRONG! /sony/tasks will think that "tasks" is a username…put above the "resources :users, …" line
     end

 

Posted in Coding, Ruby/Rails, Technology | Comments closed

Beginner’s electronics soldering project: Led Origami Flower

Ok, so its been some time since I’ve done any soldering, so I figured I start with a small attainable project before I move on to my project of building a cigar box speaker(http://blog.makezine.com/projects/make-34/monobox-powered-speaker-2/).

Since I ordered some parts from Jameco, I went with their LED Origami Flower project as my starter project.

So, the premise of the LED Origami Flower Kit is pretty basic. You solder some RGB Led’s to a wire, and plug the wire into a breadboard that has a power supply with 3×1.5V AA batteries.

Following Jameco’s instructions was not the easiest thing.  There is a large caveat at the beginning of the website’s instructions(there are a slightly different set of instructions if you download the user manual pdf, rather than html), where they warn that users are burning out their led’s from the soldering iron, and they give tips on recommended ways to solder.  However, when you get to the part of the actual instructions on soldering the leds, it was very confusing(to a beginner) how to actually manage it.  Particularly because in the design of the flower, you use the wire of soldering to the led is coiled up and serves as the stem to the flower.

Needless to say, I killed two of the 3 included leds.  On my first LED, I followed the instructions to the T and coiled the wire first before soldering.  Even with my trusty helping hands,

Helping Hands soldering tool

Helping Hands soldering tool

it was impossible to get the leads of the led touching the stripped wire and held long enough for me to solder it.  So I decided to to solder first and coil, and this definitely seemed like a better approach.

I still killed the 2nd led, although i did a slightly better job as it only slightly still lit up after soldering it, but then i short circuited the led by somehow mashing the two leads of the led to touch together while plugged in.  don’t ask.

Ultimately, third time was the charm though as I figure out how to coil it with the leads of the LED inside the coil.

With the led soldered and lighting, all that was left was to make an origami flower.  The kit recommends the tulip, lily or kusudama.  The kusudama requires glue, so I chose the lily.  It was pretty easy.

 

 

 

Lily Origami Flowers

Lily Origami Flowers

Took a few tries to get it right, but again, 3rd time was the charm.  I cut a little snippet smaller than the size of the led.  This gives it some tension around the led after you slide it over.  I had to triple up wrapping scrap wire(salvaged from the 1st two leds) around the stem to give it enough stiffness to stand upright.  The lily is pretty top heavy; this is possibly because I just used an 8.5″ sq(when the recipe calls for 6″).  With origami, to get that extra level of detail, your squares must be perfect so you get precise folds.

Since I burned out my first two leds, I don’t know if its worth ordering 2 more until I have a reason to order more stuff from Jameco.  However, its still pretty cool with one led.  Basic, but cool and tiny bit challenging(in a good way) for a starter project.

Led Origami Flower

Led Origami Flower

 

 

Posted in Electronics, Projects, Technology | Comments closed

Rails deployments from 4 minutes to 40 seconds

Currently my deployment(which is pretty close to a default setup) takes about 4 minutes.  Currently we take the server offline into a “maintenance” mode for the entire deployment process.  That’s 4 minutes of downtime.  No bueno.
Here’s what we’re going to do:
  1. 1. Move the maintenance mode (think of it like a mutex) to wrap only the most critical parts of the deployment
  2. 2. Make asset compilation happen offline
  3. 3. Investigate unnecessary rake tasks and scripts that load full Rails environment
Maintenance Mode

It would be great to have zero downtime deployments, but considering I wear the hats of lead dev, devops, cto, and probably a few others, I need quick solutions that have serious bang for buck.  So, spending the time to develop a scalable zero downtime solution for a startup that is just starting to grow traffic is not feasible.  Instead, a downtime window that is under a minute is acceptable to us.  So the first thing I did was evaluate what are the critical tasks that need to be ACID compliant.  Real quick I noticed that really the only tasks I need to have an in atomic operation are database migrations and the change in symlink that moves the app to the new version.  The deployed app is idempotent to all other changes.

Offline Asset Compilation

While the asset pipeline is a glorious thing from a development perspective, its also the bain of a Rails dev’s existence when it comes to deployment.  Compiling those assets takes forever.  A number of people have published a few ways around this.  There are even gems to help out like Turbo Sprockets which will only compile assets that have changed.

However, the fact remains that if you need to compile any of your stylesheets and js, it will take time.  This is problematic because if you take your app offline during the compilation process, it will leave your site unavailable for longer than it has to.  Even if you don’t take your site offline during the compilation process, than its hosing your box’s cpu cycles while users are using it.
Asset compilation should happen offline and the assets should be pushed up outside your deployment’s downtime window.  You should be using assets with a digest that are loaded via a manifest.yml file which references said digests, so compiling and pushing them up shouldn’t affect anything.
Well, as it turns out, someone has already solved this problem(mostly).
Robert Rostamizadeh has already handled most of the heavy lifting.  However, his solution is incomplete if you fit in either or both of the following cases:
  1. 1. You use Capistrano to put up a maintenance page for all or part of the deployment
  2. 2. You use a gem like AssetSync to handle deploying assets to the cloud
In my case, I fit into both.  To summarize, my goal here is to compile my assets locally, push them to my server, then use AssetSync to push to the cloud, all without taking the site offline.  The site should only be taken offline for critical sections of the deployment, like migrations and changing up the symlinks.
So here’s the Capistrano task I came up with:
# 
# = Capistrano Assets recipe
#
# Provides a couple of tasks for precompiling assets locally
# Assumes usage of AssetSync to deploy to CloudProvider or CDN 
# 
# Inspired by http://www.rostamizadeh.net/blog/2012/04/14/precompiling-assets-locally-for-capistrano-deployment

namespace :deploy do

  namespace :assets do

    desc <<-DESC
      Precompiles assets locally.  If you are using AssetSync, it should send them
      to the cloud automatically.
    DESC
    task :precompile, roles: :web do
      # i keep this in so that it triggers login at the beginning of the process
      from = source.next_revision(current_revision)
      run_locally("rake assets:clean && rake assets:precompile")
      run_locally "cd public && tar -jcf assets.tar.bz2 assets"
      top.upload "public/assets.tar.bz2", "#{shared_path}", :via => :scp
      run "cd #{shared_path} && tar -jxf assets.tar.bz2 && rm assets.tar.bz2"
      run_locally "rm public/assets.tar.bz2"
      run_locally("rake assets:clean")
    end

    desc <<-DESC
      Sync assets to the cloud via Asset Sync.  Must be run remotely(so it pulls remote aws credentials)
      and after code is deployed so it gets proper asset manifest to sync
    DESC
    task :sync, roles: :web do
      run("cd #{latest_release} && /usr/bin/env rake assets:sync RAILS_ENV=production")
    end

    desc <<-DESC
      [internal] Updates the symlink for assets
    DESC
    task :symlink, roles: :web do
      run ("rm -rf #{latest_release}/public/assets &&
            mkdir -p #{latest_release}/public &&
            mkdir -p #{shared_path}/assets &&
            ln -s #{shared_path}/assets #{latest_release}/public/assets")
    end

  end

end
You can see I follow Robert’s solution mostly, but with a couple of notable changes:
  1. 1. I removed his check to see if assets have changed.  His solution seemed a bit problematic as it relies on the git log to suss out what’s changed.  It sounds like an acceptable situation on the surface but I ran into some edge case issues which I won’t go into here.  TurboSprockets will take care of this for me anyway, and it uses the manifest.yml to compare digests.  That sounds a bit more robust to me.
  2. 2. Add an extra deploy:assets:sync task to handle syncing to the cloud with AssetSync gem
  3. 3. I rearranged the Capistrano callback stack see below
Investigate unnecessary rake tasks and scripts that load full Rails environment
I noticed that starting and stopping our background process(DelayedJob) was taking a while.  Its not such a big deal anymore as I’ve moved it outside the maintenance window, however it still bothers me.  Our app has several initializers that load in some optimizations and take some time to do so.  Do I really need the whole Rails environment to do so?  I’m just trying to restart a process.
Summary
To summarize, the best bet to reduce your deployment time, is to compile your assets offline, and suck in that maintenance window to only the most critical tasks.  Here’s our new Capistrano stack(in english)
  1. 1. Before we update code(“deploy:update_code”), precompile and push to server and cloud
  2. 2. stop our background processes
  3. 3. enable maintenance mode
  4. 4. symlink
  5. 5. migrate
  6. 6. restart web server
  7. 7. disable maintenance mode
  8. 8. start up background processes

40 Seconds is still pretty long for users to have to wait to use your site, but this time is mostly Passenger restarting itself and I’ll leave that to another article, probably one where I talk about ditching Passenger entirely…

Posted in Coding, Ruby/Rails, Technology | Tagged , , , | Comments closed

Capistrano Callback Sequence

Considering how well Capistrano is documented otherwise, I’m surprised there isn’t better documentation on the load order or sequence of the default capistrano tasks.

There Capistrano Deploy Recipe doc, which if you read(and who likes to do that), you can kind of figure it out.  But where are the pictures!  Google didn’t seem to turn up a whole lot, unless if you figure out the right keywords.

So take a look at this:

deploy
|-- deploy:update
|---- deploy:update_code
|------ Code update based on the :deploy_via
|------ deploy:finalize_update
|---- deploy:symlink(or deploy:create_symlink) 
|-- deploy:restart

See api rants on github

Now, I (incorrectly) thought that by specifying an after “deploy:update_code” it would run after the update_code task and before the finalize_update task.  But after seeing the above diagram, this is clearly wrong as tasks are nested, not linear.  I’m sure I’m not the only one to make this mistake.

 

Posted in Coding, Ruby/Rails, Technology | Tagged , , | Comments closed

Patterns: Exception Factory(or is it a Proxy?)

Let’s say you are writing a library that wraps around an API, say Yammer.  Your library probably uses a lower level library to manage the http requests, say Faraday.  There are a multitude of problems that may arise while communicating with their api.  For example, the user could have revoked their token, or there could be an internal server error.  Faraday will raise all of these as one or a couple of type of exceptions.  So in your library you will want to wrap these exceptions and probably raise more specific exceptions with better error messages so that client applications of your library can catch them specifically.

One way of handling this is to put the logic that determines what exception to raise right where you catch Faraday’s exception, but this isn’t very modular and extensible.  Here’s an example:

    def request(method, path, options, format)
      begin
        ....do all sorts of request stuff that might raise an exception...
      rescue Faraday::Error::ClientError => e
       #status code is given to us by faraday
       case e.status_code
       when 401
         raise Yammer::401Exception
       when 404
         raise Yammer::404Exception
       ...and so on...
        end
      end
    end

Or…you could put all the logic into an exception proxy(or factory) class which encapsulates all that logic for you, like so:

  class ErrorProxy
    def self.new(exception)
      return self.determine_exception(exception)
    end

    def self.determine_exception(exception)
      exception = exception
      message = exception.message
      status = exception.response[:status]
      headers = exception.response[:headers]

      case status.to_i
      when 400
        Yammer::BadRequest.new(error_message(message), headers)
      when 401
        Yammer::Unauthorized.new(error_message(message), headers)
      when 403
        Yammer::Forbidden.new(error_message(message), headers)
      when 404
        Yammer::NotFound.new(error_message(message), headers)
      when 406
        Yammer::NotAcceptable.new(error_message(message), headers)
      when 500
        Yammer::InternalServerError.new(error_message("Something is technically wrong."), headers)
      when 502
        Yammer::BadGateway.new(error_message("Yammer is down or being upgraded."), headers)
      when 503
        Yammer::ServiceUnavailable.new(error_message("(__-){ Yammer is over capacity."), headers)
      end
    end

    private
    def self.error_message(msg)
      "There was an error with Yammer: "+msg
    end
  end

And then:

    def request(method, path, options, format)
      begin
        ...
      rescue Faraday::Error::ClientError => e
        raise Yammer::ErrorProxy.new(e)
      end
    end

So client libraries can now easily do something like:

begin
  @yammer_client.users
rescue Yammer::Unauthorized => e
 ..handle exception
end

Ahh, much nicer.  Enjoy.

Posted in Coding, Ruby/Rails, Technology | Tagged , , | Comments closed

Capybara custom matcher alternative

Sometimes when writing specs, you want to test a high level case multiple times across multiple spec tests.  This test may involve asserting multiple things on the page.

There is probably a proper way to do this, like see this gist , or there is my way, which seems way simpler.

So the objective is to be able to express tests as follows:

page.should be_super_awesome
page.should have_super_awesomeness

To do this, you need to extend Capybara::Session.  So what I do is in spec/support/super_awesome_helper:

module SuperAwesomeHelper
  module Session
    def is_super?
       ...
    end
    def has_awesomeness?
       ...
    end
  end
end

Notice the grammar.  To have a helper that is be_something, the method needs to be is_something?  And to have a helper that is have_something, the method should be has_something?.

Then to load this into Capybara::Session

Capybara::Session.send(:include, SuperAwesomeHelper::Session)

This is all neat and dandy, but what about descriptive error messages?  Good question, watson!  Here’s a sample implementation:

 

module SuperAwesomeHelper
  module Session
    def super_awesome?
      errors = false
      errors ||= "Wrong path" unless current_path == super_awesome_path
      errors ||= "Missing content: You are awesome" unless !errors and has_content?("You are awesome")
      errors ||= "Missing selector: #awesome-div" unless !errors and has_selector?("#awesome-div")
      People.all.each{|p| errors ||= "missing person #{p.name}" unless !errors and has_selector?(".person-#{p.name}")}
      !errors or raise Capybara::ExpectationNotMet, errors
      return true
    end
  end
end

The magic line here is:

!errors or raise Capybara::ExpectationNotMet, errors

which is what tells capybara to catch the exception and handle it properly.  You’ll notice my pattern here will stop checking for errors(essentially) once you hit the first error(if, at all),

which I think is ideal.  But you could implement it differently so it spits back all the error messages.

Thanks for listening. :)

Posted in Coding, Ruby/Rails, Technology, Uncategorized | Tagged , | Comments closed

Ec2, Elastic LoadBalancers, Passenger, forcing ssl and how not to drive yourself crazy

Say you are using ec2, elastic load balancers and passenger to run your rails app, and then say you want to force ssl for all requests.  If you’re running a Rails 3.1+ app you just need to specify force_ssl, right?  nope.

Do these things and save yourself some time, money, and hair follicles:

  1. Change the loadbalancer health check to check https
  2. Don’t use passenger standalone!

We had been using passenger standalone with a reverse proxy in apache and it worked pretty well until I needed to implement a maintenance page and force ssl.  You could probably get it to work but you need to make sure to pass some headers around and thats beyond me.

I installed passenger properly on our CentOS box with a minimum of frustration, and even got it to work via rvm. Protip: make sure to run passenger-install-apache2-module as the user who normally runs rvm and when you do you’ll get a code snippet to put into your apache conf that is rvm specific. woohoo!

all is right with the world once again

 

Posted in Coding, Ruby/Rails, Technology | Comments closed

ProTip: Don’t name your namespaced controllers “ApplicationController”

Don’t do this:

class Admin::ApplicationController < ApplicationController
  layout "admin"
end

class Admin::IndexController < Admin::ApplicationController
end

This works for the most part except that the layout is not chosen properly.  Rails just chooses the default application.html.erb layout.

Instead, rename to something like this:

class Admin::BaseController < ApplicationController
  layout "admin"
end

class Admin::IndexController < Admin::BaseController
end

you’re welcome.

 

 

Posted in Coding, Ruby/Rails, Technology | Tagged , , , , | Comments closed

Rails Nested Resource Controllers – what not to do when testing

Testing nested resource controllers is pretty easy and awesome.  It is not easy and awesome, however, if the name of your nested controller differs from the route you want to use.

Examine the following

resources :posts do
  resources :comments, controller: "UserComments"
end

Did you catch whats wrong with the above?  You may not actually run into any problems with the above code if you don’t do functional tests for your nested comments controller.

I had the following:

require 'spec_helper'

describe UserCommentsController do
  it "should create a comment" do
      expect {
        post :create, {:post_id => 1}
      }.to change(UserComment, :count).by(1)
  end
end

which yielded the following error:

Failure/Error: post :create, {:post_id => 1}
     ActionController::RoutingError:
       No route matches {:post_id=>"1", :controller=>"user_comments", :action=>"create"}

So weird, this is exactly how the requests looks when I access via a web browser, so what gives?  Well, after some excruciating digging into Rails route sets and route generation code, and finally bottoming out at some method called “non_recursive” which is actually where the meat of the route matching occurs, I finally realized the casing was wrong in my route set.  When specifying a controller, use underscore notation!

so for the love of buddha:

resources :posts do
  resources :comments, controller: "user_comments"
end

Why does the server match the route properly but not the tests! le sigh…

Oi, hope this helps someone else in the future, or me when it happens again…

 

Posted in Coding, Ruby/Rails, Technology | Comments closed

Capybara, ajax, requirejs and how to pull your hair out in 8 easy hours…

Editors Note:  I wrote this post after a full day of hair pulling and shotgun debugging, so it may be a bit incoherent…but I wanted to get the situation documented as soon as possible.  Read at your own risk

Capybara is awesome for rails acceptance testing. However, I do have a love/hate relationship with it. For every hour its saved me in avoiding regressions, I’ve definitely had a few hours of hair pulling trying to get it to work properly, particularly with regards to javascript and ajax usage.

Currently, I’ve spent many hours trying to figure out why my tests were intermittently passing when testing a registration form that was submitted via ajax.

The first issue I had to come to terms with is that capybara will not know when asynchronously loaded javascript files have loaded(think requirejs).  This is a problem if you attach behavior to elements via one of these files.  Capybara will try to interact with your elements but they will be missing some behavior because those files may not have loaded yet.

The second issue is that Capybara doesn’t play nice when you do a full redirect via javascript.  It doesn’t seem to execute the redirect until after the spec example group is completed.  The solution I came up with is to “stall”(or in computer speak, block) Capybara by using one of its own matchers that knows how to wait if an element its trying to match on is missing.  The two methods I figured out that do this are “visit” and any of the matchers of the “have_selector” or “have_content” variety.

For brevity, my specs looked something like this:

context "when loading page" do
  before(:each) do
    @initial_user_count = User.count
    visit new_user_path
    page.fill_in :login, :with => "John"
    page.fill_in :email, :with => "john@example.com"
    page.fill_in :password, :with => "password"
    page.fill_in :password_confirmation, :with => "password"
    click_on "Register"
  end

  it "should create user" do
    User.count.should == @initial_user_count + 1
  end

  it "should show homepage" do
    page.current_path.should == root_path
  end
end

So the problem here is that when a user clicks on “Register”, an ajax request is sent off which submits the form, and if everything is ok, it will redirect the user via javascript.  The behavior I’m seeing is that capybara doesn’t seem to execute the javascript redirect, unless I use a matcher of the form have_selector, like have_selector(“#user_nav”).  So one solution was to put this in the before(:each) block:

click_on "Register"
page.should have_selector "#user_nav"

This seemed to do a decent job of fixing the problem, but there was another issue that took me a half-day to figure out.  In the end, I realized that I was getting intermittent passing results while I was perfecting the spec’s because of a weird situation with DatabaseCleaner.

The relevant portion of my spec_helper.rb looked like the following:

    config.before(:suite) do
      DatabaseCleaner.strategy = :truncation

    end

    config.before(:each) do
      DatabaseCleaner.start
    end

    config.after(:each) do
      DatabaseCleaner.clean
    end

So, what was happening was that my spec fired off an async request to add a user instance, but before that actually hit the server, the spec example was completing and DatabaseCleaner did its just of truncating the tables.  But then, lo and behold, the request made its way to the server, and added the user instance, leaving me with a dirty database!  This of course led to the next spec failing because a user with those credentials already existed, but of course the reason why wasn’t clear…because during this run, DatabaseCleaner did its job at the appropriate time and thus the test would pass on the next round….madness!

So the full solution involves forcing DatabaseCleaner to fully cleanup after the suite has run:

    config.before(:suite) do
      DatabaseCleaner.strategy = :truncation
      DatabaseCleaner.clean
    end

    config.before(:each) do
      DatabaseCleaner.start
    end

    config.after(:each) do
      DatabaseCleaner.clean
    end

    config.after(:suite) do
      DatabaseCleaner.clean
    end

And the full spec solution:

  before(:each) do
    @initial_user_count = User.count
    visit new_user_path
    page.fill_in :login, :with => "John"
    page.fill_in :email, :with => "john@example.com"
    page.fill_in :password, :with => "password"
    page.fill_in :password_confirmation, :with => "password"
    click_on "Register"
    page.should have_selector "#user_nav"
  end

  it "should create user" do
    User.count.should == @initial_user_count + 1
  end

  it "should show homepage" do
    page.current_path.should == root_path
  end

UPDATE(8/7/2012): Thanks to @badeball on github(https://github.com/jnicklas/capybara/issues/771#issuecomment-7552948), I was able to fully iron out the issue when assets weren’t loading fast enough and capybara would try to click a link before the remote form processing event handlers had been bound.

So I created a helper: spec/support/asychronous_helper.rb to handle the various ui cases I needed to wait for:

#/spec/support/asynchronous_helper.rb
module AsynchronousHelper

  def wait_until_remote_events_are_bound
    page.wait_until do
      page.evaluate_script("typeof($assetsloaded) === 'object'")
    end
  end

  def wait_until_overlay_has_popped_up
    page.wait_until do
      page.evaluate_script("$('div.overlay').is(':visible')")
    end    
  end

  def wait_until_overlay_disappears
    page.wait_until do
      !page.evaluate_script("$('div.overlay').is(':visible')")
    end
  end
end

Bam!

Posted in Coding, Ruby/Rails, Technology | Comments closed

Get more reliable wifi in remote areas: carry an extender

So you’re not gonna believe this next tip.

Carry around a wifi extender.

Yup, I said it.  and I’ve been doing it. I bought it in Germany, and its been with me down through Eastern Europe and now India.  I’ve been meaning to ship it home…but I keep delaying and it keeps getting me wifi in my rooms that don’t ordinarily have it.

The wifi extender will have stronger receive  and transmit power than your computer or cell phone so it’ll even make weak signals more reliable.

It really isn’t adding a huge weight or burden either.  Its not bigger or heavier than my lonely planet india book.

Fyi, the model i’m using(and i’m not paid to say this, though i wish i were – not really) is the Netgear WN2000RPT.  Its a rugged bugger as its been knocked off windows and dropped out of backpacks more times that I’d like to admit and still working great.

Posted in Tips, Travel | Tagged , , , | Comments closed

How to download a large file with a shaky internet connection, the 1337 way.

When traveling, the availability of a solid connection isn’t always reliable.  Or sometimes the file is so large and you are in transit you need to chip away at the download each time you find bits of access.

Some browser download managers might support resume, but as of writing, Google Chrome does NOT.  pitiful, Chrome, I love you, but pitiful.

So, recourse is to find some other download manager that supports resume?  Not quite.  That is if you’re using a proper OS.  Any OS with wget is what you need.

2 steps:

1st make sure the webserver supports the HTTP range header(most will)

curl -I <theurltothefile.iso>

2nd wget that badboy

wget <theurltothefile.iso>

and after the download gets interrupted and you need to resume

wget -c <theurltothefile.iso>

fin.

Posted in Tips, Travel | Tagged , , , | Comments closed

Know where you are always: offline mapping on Android

So, you’re in the middle of india and you need to find your guesthouse.  No one speaks english.  You can’t call for directions.  All you have is an address.  Out of luck?  Not on android.

The latest version of Google Maps on Ice Cream Sandwich has the ability to pre-cache all the maps tiles within a given radius.  That means full zoom in/zoom out capabilities with street names and major landmarks at all levels.  oh yea.  unfortunately, no searching.

So to begin, make sure you’re on a decent wifi signal

1st enable the labs feature for pre-caching

There are 2 ways to activate the pre-caching

A. if you long press on any arbitrary point on the map, or click on your gps location, you will get a speech bubble.  Click this and you get the maps page for this location.  You’ll see options for “What’s nearby”, “directions”, “call”, etc.  Below these, you’ll find “pre-cache map area”

B.  If you search for an establishment or a starred location, its a little different.  Once you click into the speech bubble, you’ll see things like photos, and an icon for map, and directions.  Here, you’ll need to click the menu, to bring up the option to pre-cache

 

Once, you click pre-cache, it will take a few minutes for the tiles to download and you will see a black square which indicates the “radius” or rather perimeter that is pre-cached.

You can now disconnect from wifi and go get lost!

 

Posted in Tips, Travel | Tagged , , , | Comments closed

Ubuntu 10.04, Rvm, and Rails 3.1.3 from scratch

Assumptions:(swap these out  in the below notes as you see fit)

  1. database: mysql
  2. scm: bazaar
  3. testing: capybara(has a libqt dependency)

do basic install ubuntu 10.04
do full software update

apt-get install build-essential curl git-core ruby zlib1g-dev libxml2-dev libxslt1-dev emacs mysql-client mysql-server libmysqlclient-dev bzr libqt4-core libqt4-dev

rvm pkg install zlib openssl curl readline
rvm install 1.9.2-p180 --with-zlib-dir=$rvm_path/usr --with-openssl-dir=$rvm_path/usr --with-curl-dir=$rvm_path/usr --with-readline-dir=$rvm_path/usr
rvm use 1.9.2-p180 or rvm --default use1.9.2-p180
gem install bundle
cd work/
bzr co sftp://USER@DOMAIN/home/branch/trunk/
cd trunk
cp config/database.yml.config config/database.yml
edit with relevant db info
bundle install
Posted in Coding, Ruby/Rails, Technology | Comments closed

ActiveScaffold and Rails 3.1.x without Asset pipeline

We have recently upgraded an app to rails 3.1.3 and to keep things simple(or so we thought) we avoided jumping into the asset pipeline.

As expected, with rails, whenever you go against the grain, expect problems.

The app was working mostly, until we tested ActiveScaffold.  First off, I despise AS.  It has definitely caused me more headaches than it purportedly saves.  In rails 3 land, scaffolding is dead simple anyway, so why not build from scratch?

But alas, this is a legacy system, and we don’t have the luxury of ripping AS out and starting from scratch.

So, the first error, that we came across is:

undefined local variable or method `active_scaffold_includes'

I’ll spare you what it took to get this to work…Almost all of the tutorials say to use Vhocstein’s fork.  But as it turned out, this solved the initial problem, but I was getting a ton of other random issues like “ActiveRecord::InverseOfAssociationNotFoundError” errors.

In the end, I’m resorting to monkey patching until the official gem catches up.  I copied the “lib/active_scaffold/helpers/view_helpers.rb” file into “/lib/active_scaffold_monkeypatch.rb” and required it in application.rb

That solved the first issue.

To really get up and running I had to also do the following:

  1. We also were moving away from Prototype, and because I’m not using the assets pipeline, I had to make sure the proper jquery files were located in “public/javascripts/active_scaffold/default”.  You can find them in  the AS gem under “app/assets/javascripts/jquery” and just copy them over and remove the old Prototype files.
  2. Also, you cannot rely on
    javascript_include_tag :defaults

    You must explicitly include the jquery files(we use google cdn, cuz we’re cool like that)

        = javascript_include_tag "http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js", "http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.min.js", "application.js"
  3. We updated our config/locals/en.yml to have
     en:
       hello: "Hello world"
    +  time:
    +    formats:
    +      default: "%a, %d %b %Y %H:%M:%S"

 

And that’s it, I think…our spec’s are passing as of now.

Posted in Coding, Ruby/Rails, Technology | Comments closed

Letters from Istanbul – Part II

Hey all,

I’ve caught a head cold so I”m not really into making this story pretty right now….Istanbul is still awesome.  The kindred connection between Istanbul and NY continues as I meet more and more Turk’s and Istanbulers.  I think it also shares a similarity in that its probably a nice place to visit, but to live long term, its probably not so nice.
Yesterday, I went to the Prince’s Islands which is this chain of islands in the Sea of Marmara.  I went with a group of people I wasn’t really familiar with, but in the end it happened that the group widdled down to 3 of us.  There was Reme, 18, from Hamburg and Marwon, 25, from Australia.   All 3 of us were website developers, vegetarian, and had an ongoing photo series of handstands around the world.  Twas quite weird.  However, Marwon was an atheist, and Reme was on the way to being one.  So, phew, we weren’t complete doppelgangers.
We found out that there was a free whirling dervish performance, so our plan was to go to one of the 2 peaks of the island and make it back for the performance at 4.  However, after we finished snapping handstand photos at the 1st peak, we biked down.  On the way, Reme’s bike basically fell apart, kind of like the coyote and the road runner, when the coyote builds a contraption to fly off a cliff and piece by piece just drops away and the coyote pauses, blinks, and then gravity sets in. Yes, it was kind of comical despite its annoyingness.
There was no way we would make it back to the developed portion of the island to make it back in time for the performance  So now we had more time to stay on the undeveloped part and hiked up to the other peak where there is the 2nd largest wooden building in the world: an abandoned WWII-era orphanage.
This massive dilapidated structure sits at the top of the hill with nothing other than trees and wild horses roaming the steep green hills.  I pictured this orphanage in some black and white hitchcock film during a stormy night.
Marwon is a bit crazy and thought it was a good idea to hop the fence and get a closer look at the building.  While Reme debated hopping, I stayed put and watched for security.  Within a few minutes, the guard dogs caught Marwon’s scent.  Earlier we had seen a guard dog, but on a chain leash.  When the barking started, I could clearly see, these dogs were not chained.  Marwon raced back, and reverse-hopped the fence, but sliced his hand open in the process.  Not too bad, but the fence was one big tetanus playground, so he’ll have fun finding a doctor today for his booster.
We split immediately and didn’t wait to find out if the dogs were all bark and no bite.  So we dashed down and around the hill the orphanage sat on top of.  After we got a good distance we just wandered along the incline through the trees back around to the front where we parked our bikes and happened to find a damn near pristine horse mandible and femur.  reme posed for a photo op with the horse mandible next to his own.
We made it back in time for the 2nd to last ferry back.  Only, both this and the last one were cancelled.  Finally, we figured out that there was a private operator running one last one back to the mainland.  It was chaos and confusion to find out where it was and how to buy tickets, but we figured it out and made it back in time for saturday night party.
Fyi, I arrive in India on the 26th.  Love you all,
Pete
Posted in Travel, World Trip 2011/2012 | Comments closed

Letters from Istanbul, and a (brief) story of Transylvanian misadventure

After again trying(unsuccessfully) to wrangle the Romanian banks to accept my bank card, I cashed in my emergency dollars, leaving one last Jacksonin my pocket to contemplate whether he’s worth more than the lint he sits next to.  Or perhaps hes an optimist and looks towards brighter times in lands where he’s respected.  In either case, neither of us were prepared for the remainder of the day.

After being disappointed with the dracula paraphernalia in the tourist shops, I decided to scope out the mountain peaks that lear over Brasov that were now revealed from yesterdays fog.  On one side there was a peak with a massive radio tower and giant block letters “BRASOV” ala Hollywood.  Cool.  And a cable car to get to the top?  Word.  As I walked up to the base of the cable car station, the backside was boarded up and covered with graffiti.  There was no one around and I wasn’t even sure if they were open, but I proceeded around to the front.  I read a sign that said “Last up 4:45p”.  It was 3:30.  sweet.  15 Lei’s($5) and 10minute wait by myself next to a brick furnace, and a weathered old romanian comes out, unlocks the car and takes me to the top.  I take video as we ascend and notice the car on the other side is full of people descending.  hmmm.
I get to the top and see a door to a restaurant and figure I’ll check it out after taking some snaps of the peak.  There is deep snow everywhere and a hill up to where a Romanian flag is flapping.  The wind is blowing like its determined to blow the mountain over.  The mountain held its ground as mountains tend to do.  Though somehow the wind wasn’t too strong down by the ground, but it howled above me.   still no one in sight….kind of spooky.  screams probably get lost easier than hikers do ’round these parts.  I climbed the small hill in the snow and did the myspace angles in front of the flag…you know the ones where you try to look aloof as you snap a pic of yourself with an outstretched arm…
Not really satisified with my $5 spent, I followed a small trail round the backside of the mountain with a mind to keep it quick as the sun was setting soon.  And I still haven’t seen a soul besides the man who took me up.  Turns out the small trail led to the BRASOV sign with one of the most amazing overlooks I’ve ever seen.  It was also kinda one of the scariest with a steel platform hovering over the cliff with a thigh high railing.  A fenced off cave opposite the platform wrapped a grave with a cross tombstone of some famous Romanian.  Hopefully there was no relationship to the thigh high fence….
The visibility was crisp and I could see way out into the Romanian landscape with the wrinkles of the snow capped Carpathians slumbering out to the right.  I wasn’t sure why they called the black church and black tower black, but up here jutting out against the terracotta roof terrain of Brasov, it kinda made sense.
So, 4:15pm…I should probably get back.  I trudge back through the snow  and no one is still around.  The wind is fierce now.  The entrance to the platform is locked, probably a safety thing, but no one is around.  There is a laptop bag filled with bread and rolls sitting on a garbage can.  I go to the restaurant…its closed.  I go door by door around the facility, everything is locked.  Hello? I start saying.  Then I start shouting out to call for someone.  HEEELLLLLOOOO??  Nothing.  Visions of a Dracula themed Shining are flashing through my head.  I run around the grounds banging on doors and shouting….nothing…I take a breath and watch the sun start to dip below the horizon….oh fuck.  I call my friend here who happens to be an accomplished mountaineer.
Uhhh… Mihai?  I might have an issue…
Yea, I think they close the mountain at 4 and they don’t really count who goes up there.  

So umm…

Its cool dude, there’s still plenty of light, you can walk down.  

ok, umm… 

walk to the where the BRASOV sign was and before you get there…

ok, i’m walking there now…(sprinting actually)

…theres a dip to a trail head that you can take down and it winds down until it drops you right into the old city center.  Just make sure you can see the cable car cables, and you’re fine.  

HOOOONKKKK….HELLLLOOO….HONNNNKKKKK

Oh fuck mihai, i think they’re calling for me, call you back…

hey mihai, damn, they left, just as I got to the platform…headed back to the trail now…I know where it is…call you if i have any problems…

As I’m halfway down the craggy, snowy mountain, I see a car going up…what the deuce?
I made it to the bottom by 4:45 on the nose and approached the base house for the cable car.  The lady who sold me the ticket is locking up and the sign still reads “last up – 4:45pm”.  arg…
Umm just so you know I’m not still up there, I thought you closed at 4pm(pointed to my watch) and left without me, so I walked down

Tomorrow, tomorrow,  we closed, you come back tomorrow.

Fucking hell, she thinks I want to go up.  Where’s the vin fiere(hot wine), I need a drink.
Fin.
After, I went out to dinner with Mihai(my saviour), his girlfriend, and her sis to a great restaurant.  Art nouveau posters and white vignetted portraits of people with curly mustaches, bowler hats, giant dresses and expressionless faces.  Ragtime music played live on a grande.  Garland and gingerbread cookies along the railings.  small golden lampshades with fringe that stood still.  gnocchi with walnuts and Ciuc(chiuck) beer.
What a day.
The next morning I had an 8am 24hr long train to Istanbul via Bucharest.  Mostly uneventful except for our stop at 2am at the Turkish border where I didn’t realize I had to buy a visa.  All my cash is now is in Romanian lei’s and yup, they only take Euro’s or Dollars.  How much is the visa?  15 euros or $20…cash machine? nope, exchange office? nope…wait!  I’ve got that last Jackson in my pocket that I saved from before….thank god i’m not canadian(their visa costs $60…)
…and so…I’m writing you from my hostel in Istanbul where the atm’s accept my bank card, its warm(er) and life is good again.
love you,
Pete
Posted in Travel, World Trip 2011/2012 | Comments closed

Letters from Transylvania

Hey all,

Transylvania!!!  :::insert megalomaniacal laughter set to tochata and fugue::::  actually i’m in a town called Brasov in the region of Transylvania.  Its close to Vlad the Impaler’s castle…so I’m gonna try to make it there tomorrow.  So Vlad the Impaler was actually dracula.  Dracula just means son of the dragon and his dad was the dragon(Drac)…or something like that…
So far its only kind of creepy here.  The train ride last night was amazing.  Really old train that creaked, squeaked and moaned through the night.  The moon was out on one end of the sky partially obscured by thin strips of clouds…and the other end was completely clear with an amazing view of the stars(even with the moonlight)…I laid in my sleeper and saw several shooting stars.  The sleeper car was mostly empty so I had my own room which was awesome because its tiny!  Occasionally there would be loud voices of large men stomping through the hall but my room locked from the inside which was cool…especially since the conductor who was really nice warned me several times to make sure I locked ALL 3 of the locks on the inside…
I’m pretty happy to be out of Hungary.  They say hello and goodbye by saying “Szia”  which is pronounced “see-ya”…so sometimes its easy…and other times its really confusing when you walk up to them and they smile and wave and say “see-ya”.
Arriving this morning was neat…had the first feeling that I was kind of out Europe.  Prague and Budapest were both very european.  Really all the amenities an american might be used to were accessible one way or another.  Both had H&M and KFC and a bunch of other transnational acronyms. But coming into romania, at least from the comfy view from my sleeper, I saw a 50/50 mix of cars and horse drawn carriages and lots of aluminum and straw shanty towns with steaming compost piles.  Maybe its just cuz i’m in a smaller town as opposed to a big city…Although, I did spot a KFC here in Brasov…
Romanians all seem really nice…and the language sounds like Italian(you’re right leslie :) )  Every time I’ve whipped out my map someone checks to make sure I’m not lost and if I need help.  Most, if not all, of the time they’ve seemed genuine.  Very few people speak english.  In fact I think german is more common, which is really interesting.  Signs are more often in German than in english.  The train station was definitely filled with some ruffians(yea i said ruffians).  Even witnessed a fight within 5 minutes of arriving.  But I kept to myself and changed some money to Romanian Leu’s and got on the bus to my hostel
So now I’m officially 2 cities behind on photos….and of course when i went to upload them in Budapest where I had fairly stable connection…it crapped out in the hostel…so as soon as i get a chance I will get them…The train ride to istanbul is 18hours so that might be a good opportunity for me to at least get them on my computer and bagged and tagged.
I’m tentatively scheduled to go to Istanbul on Friday, but I might delay to give me more time in vampire country.  I”ll keep you posted :)
Love you all!
Pete
Posted in Travel, World Trip 2011/2012 | Comments closed

Letters from Budapest

Hey All,

Just arrived into my hostel in Budapest!  It was crazy this morning getting out of Prague so I didn’t have time to send a “leaving prague” email, but alas, i’m safe and sound in freezing but beautiful budapest.  Did you know budapest is really 2 cities: buda and pest.  Also, “pest” isn’t pronounced like “pest”, its pronounced “pesht”.  In case you were wondering…
Prague was very awesome.  Even after a week I still didn’t get a chance to see all the major attractions.  Its really interesting there because you can go from medieval, to baroque, to renaissance, to cubist(!) art and architecture within a very short distance.  Then there is also this czech artist who’s done some very amazing artwork like a sculpture of 2 dudes pissing on the map of the Czech republik.  This same artist was also commissioned by the EU to do an artwork that was demonstrative of the cultural diversity of the EU…and so in 2009 he did this: http://www.spiegel.de/international/europe/0,1518,601209,00.html Check out the photos…quite hilarious…
The whole city is walkable from one end to the next.  The only complaint is that its a bit touristy…its difficult to find a bit of “old worldness” that doesn’t have an annoying souvenir shop at the bottom.  My friend Martina who I stayed with for some days wrote me these directions half in czeck for off the beaten paths wonders…and i definitely got off the beaten path and found a monastery that brewed their own beer. yum.
While in prague, I attended a Cannabis conference…yes a Cannabis conference.  I saw on the program that they had a couple of lectures of hemp as a renewable building material…so this was totally the only reason why I went.  to check out renewable building materials.  Unfortunately, the lecture was completely in Czech…they had translation but it was still very difficult to understand.  I still enjoyed the rest of the conference, surprisingly. :)
I took a lot of photos…mostly from my phone…will try to get them uploaded shortly once they’re bagged and tagged.
love you all!
~pete
Posted in Travel, World Trip 2011/2012 | Comments closed

How to *Not Really* delete a ruby class from memory

Alright, alright…(first blog post here, cut me some slack…)

So, how can you delete a class from memory in Ruby?  First, you might be asking….why in the hell would you do that.

Well, as it happens, in my case, I wrote some base classes that other developers will derive off of.  So in this base class I wrote code that enforces that any class that inherits off it it will conform to the prescribed interface, otherwise it will throw an error.  So, of course, I wrote test code that tests this behavior(what am I a farmer?).  This is where I had the problem…

To be clear, let’s get specific:

class JobType
  class_attribute :cost
  self.cost = nil#all subclasses must define this

  def self.get_cost
    raise "subclass must define this" if self.cost.nil?
    return self.cost
  end

  def self.types
    self.subclasses
  end
end

class LogoJobType
  self.cost = 100
end

So, in my spec tests:

it "should raise error for improperly subclassed class" do
  class TotallyNewClass < JobType;end
  expect{TotallyNewClass.new.get_cost}.to raise_exception
end

Now this actually works fine when the test is run in isolation. However, some other tests are failing(which pass in isolation) when they are all run as a suite.

Say what?

Well, I have some other tests that are calling JobType.types. Ok…so you might be saying that I probably shouldn’t rely on Rails’ #subclasses method because you know you’ve dug into the Rails source and see its implemented using ObjectSpace which is slow and a memory hog. Well, you’re absolutely right. Now, forget that you ever remembered that.

What’s happening is that when these tests are run as a suite, TotallyNewClass is entering the JobType class hierarchy….and staying there!

So, my first thought, was ok, that kind of makes sense, maybe I should try to delete the class constant. This is ruby. I can probably do that. Nope. The only thing you can do is undefine a constant like so:

Object.class_eval{remove_const :TotallyNewClass}

However….

ObjectSpace.each_object(class << JobType;self;end){|k| puts k}#still shows TotallyNewClass

What gives? Well… As it turns out, like I said, you can’t destroy an object that a constant points to. You can only undefine that constant.

Our good friend _Why points out:

If you stuff something in an array and you happen to keep that array around, it’s all marked. If you stuff something in a constant or global variable, it’s forever marked.

See more on _Why’s thoughts on garbage collection here:
http://viewsourcecode.org/why/hacking/theFullyUpturnedBin.html

But this actually led me to the answer! Don’t use a constant. Very simply:

new_klass = Class.new(JobType){}

We dynamically create the class and then an instance off it and never assign it to a constant, and eventually the class gets swept by GC, and life is good again.

Thanks for tuning in.

Update 11/18/2011
Ok, so I started testing my app with capybara and spork…and this doesn’t appear to be working. I’m finding many instances of the anonymous class in the class hierarchy. So…I’m just going to implement subclasses myself using the inherited callback which is pretty easy and probably more performant anyway.

Posted in Coding, Ruby/Rails, Technology | Tagged , , | Comments closed