Jun 17, 2014

Jun 17, 2012

Just Maybe, Maybe - Pattern in Ruby

The original code I posted was flawed.  The gist below is modified and I think would work but it's not as clear as I'd like it to be.  I'll follow up on this soon.

I recently released a tiny Gem called JustMaybe.  This caused me to do more reading on the subject.  I ran across the If you gaze into nil nil gazes also into you post.  In the JustMaybe readme I sort of mention this but I wanted to express it more clearly here.

I don't really think using Maybe mixed in with the logic of your application is a good idea.  As an example I think the problem presented in that article could be solved much more clearly with this bit of code.  Here's a solution that will never return nil.



My suggestion is that if you find yourself wrestling with possible nil return values .  See if you can turn the operation on it's head.  Don't ask your object about it's associations.  Ask the association about your object.  I often find this will clean up the logic.

I did however just release JustMaybe so obviously I think it's useful in some way?  For me that's almost strictly in presentation.  When you are presenting information you often have to reach deep down into the hierarchy of objects to extract the necessary bits.  Interestingly, at presentation, is when I think you should be deciding what to display when information is missing.  To me that creates a perfect situation for using the Maybe pattern.


Feb 27, 2012

Apache HTTP to HTTPS Redirect


Here's a micro-nugget. The following Apache config redirects incoming HTTP traffic to the equivalent HTTPS page. Nothing special but I don't spend enough time working on Apache configurations to keep this stuff fresh in my mind so I find it useful to record what I learn in case I need to do it again later.

<virtualhost *:80>
  RedirectMatch permanent /(.*)$ https://example.com/$1
</virtualhost>

<virtualhost *:443>
  ServerName example.com
  # config...
</virtualhost>

Feb 20, 2012

Extending Date Parsing In Ruby 1.9.3


I had previously made posts about parsing user supplied dates in Ruby



Apparently in Ruby 1.9.3 the Date library was re-implemented in C for performance and of course that broke my extension.  I updated it to support Ruby 1.9.3 below




This may not work on Ruby versions prior to 1.9.3 I didn't try it.

I also found the american_date gem which apparently existed before I had originally written my extension and is almost certainly a better choice if you don't need any custom formats.

Feb 6, 2012

Generic ".rvmrc" File For Ruby Projects


I'm really lazy and have started using the exact same ".rvmrc" file for all my Ruby projects....

rvm use @$(basename `pwd`) --create

I'm not sure but I think I first seen this exact format while reading this code https://github.com/dkubb/veritas

Jan 27, 2012

Generic "config/database.yml" for Postgres

I'm really lazy and always use the exact same "config/database.yml" file with my Rails projects....

Jan 7, 2012

What The Hell Is SOPA?

Here's some links and a bit of explanation if you're new to the debate about SOPA.

I think the best place to start is this clip from "Up with Chris Hayes" on MSNBC which provides a fairly good intro.  The biggest problem I have with this video is that NBC exec, Richard Cotten, is never challenged in his assertion that it only covers foreign sites.  You can see Fred von Lohman, a laywer from Google and the EFF, in this video from the Standford Center for Internet and Society rebuff Cotten's position.

In the first video a poor attempt is made to present Internet piracy as a service problem.  That happens to be a view I agree with.  I think it's expressed much more eloquently by Tim O'Reilly in this Gigaom article or by Gotham Gal in this AVC.com post.  

Richard Cotten argues against "the service problem" by pointing out that Netflix, Hulu and others exist.  What he doesn't mention is they're prevented by licensing from providing the content consumers want.  In this blog post you can see Netflix only had 5 of the top 100 box office titles available last year.  The best score was by Amazon which only had 45 of the top 100 titles, less than half.  


Until they make the content available when people want to see it on which ever device or service they want to view it they have no footing in the argument against it being a service problem.


There's a ton more material out there but that's a good start if you're new to the topic.

Jan 6, 2012

More Parsing User Supplied Dates and Times in Rails


Rails does a pretty good job of making work with time zones feel transparent.  If you do everything it's way, including use ActionView::Helpers::DateHelper.  If you use a Javascript control that returns a text input field or if you allow the users to enter values directly or need to process uploaded content things get a bit more complicated.

If the string returned by the text input can be parsed by Date._parse your in luck.  Everything will still work as expected with no extra effort.  If on the other hand you want to do something as simple as display U.S. style dates, in the format "MM/DD/YYYY", you will have to manually parse the input.  Ruby's Date._parse understands 'YYYY/MM/DD' and 'DD/MM/YYYY' but not 'MM/DD/YYYY'.  In the case where you're processing the input from a Javascript control the most direct solution is to do something like this...



The example above does return a time value in the current timezone and will work as expected.  One big problem with strptime is that it isn't very flexible, the input string must match the provided format string exactly right down the the separator characters and spaces.  So this approach can work if your processing the output of a control but tends to fail if you need to process human input.

Another problem I have with the approach above is that it quickly becomes incredibly redundant if you're working with a large number of date/time fields in many different models.  To Dry that up a bit I decided to move my specialized processing into a modified version of Date._parse.  This means I don't have to litter my controllers with date time parsing code and I have a single entry point to test that all desired formats are supported.



Basically all this is doing is taking the input string and re-arranging the values into an order the original method will understand.  The biggest disadvantage to this problem is that it doesn't support per-locale input formats.  It guess I'll cross that bridge if I ever get to it.

Another Quick Rails/Postgres Tip


Assuming your local timezone is not 'UTC' you most likely will want to configure Postgres to use it anyway on your development machine so that your development environment behaves like your production environment.  To do this just find the 'timezone=' line in postgresql.conf and set it to 'UTC'.

Jan 4, 2012

Parsing User Supplied Dates and Times In Ruby


I'm in the middle of correcting some date/time handling in a Rails app. One of things that was wrong was the handling of user input date/time fields.  Obviously when users provide date/time values they're assuming we understand the information was provided from the perspective of their timezone.  Especially when we don't explicitly require them to provide timezone information.

The problem with this is that Ruby's DateTime.parse method always returns UTC based times.  You can see this clearly in the example below:
You can see the problem on the 6th line in the example above.  Even though the user input "2011/01/01T00:00" when that DateTime instance is converted to localtime the current timezone offset was subtracted.  In this case resulting in a time that's 6 hours earlier than desired.

The solution is straight forward of course. You just have to add the inverse of the users timezone offset to the value returned from DateTime.parse as demonstrated below.


On line 4 you can see it's correct even when converted from UTC to local time. 

As an alternative you could include the timezone information before parsing it but that's not always easy because you don't necessarily now the format of the user's input.


Of course all of this is generally pretty obvious but I shared just in case it can help some one less familiar with the issues.

Jan 3, 2012

Time Zones in Rails using Postgres


It appears that by default Rails creates it's timestamps in Postgres using timestamps without time zone information.  This means that if you're working directly with the database, using psql for example, and want to see local time representations you'll have to do something like this.

Specifically notice that I'm using the TIMEZONE function to re-cast the column to a timestamp with timezone.  Since the columns implied timezone is 'UTC' that's what's used.  Now that we have a timestamp with timezone we can convert that to local time using the "AT TIME ZONE" syntax.


Dec 27, 2011

More on Twitter Bootstrap in Rails


Yesterday I wrote about error handling in Rails while using Twitter Bootstrap.  One of the interesting things I was able to do with the custom form builder was move the active record attribute errors to the input fields they're associated with.  The example below is a bit simple but it should get the point across....




If you look at the template that created the form below you can see that that it doesn't include any special functionality.  All the work happens in the form builder.





If you look at the "text_field" method in the code below you can see that it just calls "input_wrapper" to add some html around the "text_field".  Since "input_wrapper" already had to test each active record attribute for errors so that it could add "error" to the classes of those elements it was pretty straight forward to tack an inline-help span on the end.





The code above is not elegant, it's just an experiment.  I certainly don't recommend using it as is but I wanted to share just in case some one is thinking about similar problems.


In general though I am fairly happy with the separation of concerns so far.  I think that by treating the multi-element fields bootstrap expects in it's forms as primitives I will be able keep my templates focused on the content and my presenters on the logic of the view.

Dec 26, 2011

Formatting Rails Errors for Twitter Bootstrap

I'm using Twitter's Bootstrap toolkit for the layout in a proof of concept application I'm working on.  So far my general impression is that I really like Bootstrap but there are a few obstacles to making it play nice with Rails.

One of those obstacles is that Rails formats fields with errors quite a bit differently than Bootstrap's CSS expects.  Below I describe a possible solution.  I'm not 100% sure this is the best approach but it seems to work well and I'm currently working on a proof of concept app that will be thrown out in several weeks so there's little risk if I'm wrong.

Rails default formatting looks like this...


Bootstrap's CSS expects this....


The solution I've arrived at is to first remove the "field_with_errors" div.  This is done by setting the field_error_proc to simply return the html passed in without wrapping it.


The next step was to create a FormBuilder subclass with the desired functionality.  The example below only demonstrates the 'text_field' method.  In practice I'll have to create a separate method for each Bootstrap form element I want to use in my application.


Then to use the custom form builder I'd do somthing like this....


I realize this wasn't exactly a detailed explanation of a solution but hopefully I managed to get the gist of the idea across.


Dec 23, 2011

Just Doing It!

Almost 18 months ago a had an an epiphany.  I'm not exactly sure what caused the thought to form but I know when it happened.  I'm certain I know when because I shared the idea in an email with a friend the moment the thought completed synthesizing it's self.

It's taken me a long time to put together a plan that I thought would let me execute on the idea sucessfully but I think I've finally gotten there.  Today, I'm shifting gears.  I'm no longer just thinking about the idea, I'm acting on it.

In fact I'm jumping in with both feet right now!

Dec 22, 2011

Simple EC2 Configuration

Over the last few years I've used different approaches to scripting the configuration of my EC2 servers. Recently I discarded a more sophisticated approach for a very simple system.  This is all pretty obvious and I'm sure you'll notice that I stole this directly from RVM but it's working out so well for me I feel compelled to share anyway.

I created a public repository of scripts on Github.  Then, like RVM, I take advantage of the fact that Github allows access to the raw content of the master branch through a fixed url.  This allows me to execute commands like the one below which will run my script for installing the Passenger gem and Apache module:

sudo su -c "bash < <(curl -s https://raw.github.com/mgreenly/aws/master/shared/passenger.sh)" -

Then I combine that with a strict set of conventions; for example I always use Ubuntu so all of my scripts assume they are being executed as the ubuntu user.  This can make some of the scripts a bit tougher to write, for example when you have to sudo su to become postgres to execute database commands, but it makes it easy to execute one script after another in a chain right from your initial login.

This approach may not compare to using tools like Chef or Puppet but I'm finding I really like the simplicity of it.

Dec 17, 2011

EC2 Friendly SSH Config

If you spend lots of time in EC2 or any other cloud service your going to collect tons of junk in your $HOME/.ssh/known_hosts file. If you're remapping domain names to cloud based servers and those IPs change SSH's default settings will prevent you from connecting until the conflict is fixed. Instead of constantly having to edit known_hosts a better approach is to have SSH ignore known_hosts while you work in the cloud.

Here's my $HOME/.ssh/config. In addition to ignoring known_hosts I also set the identiy key file and the default user.

Host *compute-1.amazonaws.com
User ubuntu
StrictHostKeyChecking no
UserKnownHostsFile /dev/null
IdentityFile ~/.ssh/your-ec2-key
ServerAliveInterval 30
ServerAliveCountMax 120


With these settings I can copy the DNS name straight from the AWS console, type 'ssh ' at the command line, paste the DNS name and then connect; example:

ssh ec2-107-100-123-99.compute-1.amazonaws.com

Nov 23, 2011

Unity fucking blows! Gnome Shell has potential.

The title may be flame bait but hopefully this will help some fence sitters in their evaluation of Unity and Gnome Shell.

The most significant factor in my statement above is that I think the Gnome Shell developers realized there needed to be a stronger context switch between using applications and managing them. In Gnome Shell when you bring up the launcher or the desktop switcher all of the applications fall away from focus and tile in the center of the screen so that the launcher and desktop switcher can be exposed. At first I found this behavior a bit distracting and figured it was all eye candy but after a while I realized just how brilliant it was.

In Unity the context switch isn't as significant. The launcher comes into view when you need it and hides when you don't. In theory anyway. In reality it's a frustrating game of whack-o-mole. The launcher is never there when you want it and it's always in the way when you don't.

It seems the Gnome developers had a much better grasp of the basic user experience issue at hand. By design or intuition they better understood that you manage applications in a different context than you use them and there was benefit in making that separation more distinct not less.

Gnome Shell certainly has room for improvement but the amount of change required to make it great is significantly less than Unity will need.

Aug 28, 2011

Almost a full year no posts!

I'm not at all sure what I'm going to do with this space.

Tomorrow would have been an entire year with no posts if it hadn't been for this one.

I have been posting on Google+ quite a bit but that's certainly no substitute for a blog.

I'm also a bit conflicted about how to focus my energy. Do I post here in a personal space? Or on a blog for my business under my name?

Oh well, when I get it figured out I'll definitely share here.






a lot but I really should blog it and link it there since the Google+ posts fade with time. On the other hand I've consideree

Aug 29, 2010

Basic Git Configuration

I recently purchased a new machine and had to configure Git again. The email/user setup it reminds you of but I couldn't remember how to configure color output without some digging. So I decided to share it here just in case anyone else may find it useful.

Jul 10, 2010

Browser Profile Backup

While I was trying to configure a specific user profile for a Selenium testing today I accidentally deleted my Firefox profile. At first I thought no big deal, my lap top (the machine I was using), is regularly backed up to an external USB drive attached to the docking station. Unfortunately for some strange reason I chose to exclude the $HOME/.mozilla/ directory that contains the profile.

I use Delicious for bookmarks so it mostly just means re-populating my tools bars and resetting passwords on rarely used sites if I can't remember them, not all that big of a deal really.

Still, I couldn't help but notice how much more I depend on the browser than desktop applications these days.