Sunday, January 15, 2012
My Blog Has Moved
I will no longer be posting at this blog. The posts and comments will remain intact, but all new posts will happen at by new site: http://scottwb.com
Labels:
blogging
Sunday, September 4, 2011
Recreate a single version of a CarrierWave::Uploader file
CarrierWave supports a simple way to recreate all the versions of an uploaded file. This comes in handy when you add a new version to your uploader, or when you change the parameters of one of them. For example, assume you have a Post class, with a CarrierWave mounted uploader on the photo column, and you have version called thumb. If you decide to change the resolution of the thumb version, and need to go back and regenerate all existing thumbs, you can do something like this:
What if you have 5 different versions on this Uploader, and you only changed one of them? The above method will download all the versions of every Post#photo from storage (think S3 or Cloud Files), regenerate all of them - even the ones that haven't changed - and re-upload all of them to storage.
That's a lot of wasted time, CPU, and bandwidth.
To address this, I've created a simple monkey patch for CarrierWave to provide a new method called recreate_version!. This method works just like recreate_versions!, except that it takes a parameter specifying a single version to recreate, rather than recreating all of them.
To use this, first drop this monkey-patch in somewhere that it will get loaded. Above your Uploader class will suffice.
Now your script to recompute all the thumbs can look like this:
This will recreate and re-upload only the thumb versions of your Post#photo uploads.
As an added side benefit, the recreate_version! method cleans up after itself. The recreate_versions! method downloads into a temporary cache dir, but leaves it up to the caller to clean that up. This new method assumes that if it had to download and cache the uploaded file and its versions, then it should clean them up immediately.
This method has turned out to save me a lot of time in regenerating large numbers of uploaded file versions. If there's any interest in this, I might work up a pull request with test cases and try to get it into the mainline CarrierWave gem release.
Post.all.each do |post| post.photo.recreate_versions! end
What if you have 5 different versions on this Uploader, and you only changed one of them? The above method will download all the versions of every Post#photo from storage (think S3 or Cloud Files), regenerate all of them - even the ones that haven't changed - and re-upload all of them to storage.
That's a lot of wasted time, CPU, and bandwidth.
To address this, I've created a simple monkey patch for CarrierWave to provide a new method called recreate_version!. This method works just like recreate_versions!, except that it takes a parameter specifying a single version to recreate, rather than recreating all of them.
To use this, first drop this monkey-patch in somewhere that it will get loaded. Above your Uploader class will suffice.
Now your script to recompute all the thumbs can look like this:
Post.all.each do |post| post.photo.recreate_version!(:thumb) end
This will recreate and re-upload only the thumb versions of your Post#photo uploads.
As an added side benefit, the recreate_version! method cleans up after itself. The recreate_versions! method downloads into a temporary cache dir, but leaves it up to the caller to clean that up. This new method assumes that if it had to download and cache the uploaded file and its versions, then it should clean them up immediately.
This method has turned out to save me a lot of time in regenerating large numbers of uploaded file versions. If there's any interest in this, I might work up a pull request with test cases and try to get it into the mainline CarrierWave gem release.
Labels:
carrierwave,
ruby
Tuesday, August 23, 2011
Adding filters to stock Devise controllers
Have some before_filters or after_filters you want to add to some or all of the Devise controller actions without having to subclass all the Devise controllers?
Here's a little trick I use: directly call the before_filter or after_filter class methods in the devise.rb initializer. For example, I have a prepare_for_mobile method that I want to apply as a before_filter to all of the Devise controller actions. This is what I have at the bottom of config/initializers/devise.rb:
Note that this is exactly the same as if you had added the before_filter call directly inside these controllers. That means if you wanted to be more selective, you could just as easily do something like:
IMPORTANT NOTE: This tactic only works reliably in the production environment. That is because in development mode, the Devise controller classes get reloaded on each request, but this config file that we've edited does not.
UPDATED 2/16/2012: See my follow-up post where I revisit this issue with a solution that works in both production and development environments.
Here's a little trick I use: directly call the before_filter or after_filter class methods in the devise.rb initializer. For example, I have a prepare_for_mobile method that I want to apply as a before_filter to all of the Devise controller actions. This is what I have at the bottom of config/initializers/devise.rb:
Note that this is exactly the same as if you had added the before_filter call directly inside these controllers. That means if you wanted to be more selective, you could just as easily do something like:
IMPORTANT NOTE: This tactic only works reliably in the production environment. That is because in development mode, the Devise controller classes get reloaded on each request, but this config file that we've edited does not.
UPDATED 2/16/2012: See my follow-up post where I revisit this issue with a solution that works in both production and development environments.
Sunday, August 21, 2011
Rackspace Cloud Files SSL Failures Over ServiceNet
I recently switched from using the public interface on my Rackspace Cloud Server to using the private interface (a.k.a. ServiceNet) for uploading files from my instance to Cloud Files. When I made this switch, I started noticing a number of intermittent "Connection reset by peer" errors.
I have reproduced this problem with both the `Fog` and `ruby-cloudfiles` gems.
To upload to Cloud Files, I'm using CarrierWave, which uses Fog, which uses Excon. With those, the error looks something like this:
I never really narrowed down why this is happening, but it seems to happen only after a period of inactivity. I.e.: it fails once, then works fine as long as I keep making requests, but after 10+ minutes, the next request fails again.
Since I am only storing files to Rackspace Cloud Files via CarrierWave, the most expedient thing for me to do was to wrap the storage call in CarrierWave with some exception handling to retry these failures. It's a hack, but it works like a charm and saved me at crunch time:
Even if you're not using CarrierWave or Fog, this concept could work for you. Of course, you may use more operations that just storing files, and you'll probably have to wrap those too.
I have reproduced this problem with both the `Fog` and `ruby-cloudfiles` gems.
To upload to Cloud Files, I'm using CarrierWave, which uses Fog, which uses Excon. With those, the error looks something like this:
Excon::Errors::SocketError: Connection reset by peer - SSL_connect
[GEM_ROOT]/gems/excon-0.6.4/lib/excon/connection.rb:264:in `connect'
[GEM_ROOT]/gems/excon-0.6.4/lib/excon/connection.rb:264:in `open_ssl_socket'
[GEM_ROOT]/gems/excon-0.6.4/lib/excon/connection.rb:243:in `connect'
[GEM_ROOT]/gems/excon-0.6.4/lib/excon/connection.rb:282:in `socket'
[GEM_ROOT]/gems/excon-0.6.4/lib/excon/connection.rb:156:in `request'
[GEM_ROOT]/gems/fog-0.9.0/lib/fog/core/connection.rb:20:in `request'
[GEM_ROOT]/gems/fog-0.9.0/lib/fog/storage/rackspace.rb:102:in `request'
[GEM_ROOT]/gems/fog-0.9.0/lib/fog/storage/requests/rackspace/put_object.rb:19:in `put_object'
[GEM_ROOT]/gems/fog-0.9.0/lib/fog/storage/models/rackspace/file.rb:59:in `save'
[GEM_ROOT]/gems/fog-0.9.0/lib/fog/core/collection.rb:50:in `create'
[GEM_ROOT]/gems/carrierwave-0.5.6/lib/carrierwave/storage/fog.rb:229:in `store'
I never really narrowed down why this is happening, but it seems to happen only after a period of inactivity. I.e.: it fails once, then works fine as long as I keep making requests, but after 10+ minutes, the next request fails again.
Since I am only storing files to Rackspace Cloud Files via CarrierWave, the most expedient thing for me to do was to wrap the storage call in CarrierWave with some exception handling to retry these failures. It's a hack, but it works like a charm and saved me at crunch time:
Even if you're not using CarrierWave or Fog, this concept could work for you. Of course, you may use more operations that just storing files, and you'll probably have to wrap those too.
Thursday, August 18, 2011
Performance of Rackspace Cloud Files Upload Over Private Network
Does using the private network interface on a Rackspace Cloud Server instance to transfer data into Rackspace Cloud files save you anything?
I am certain it saves you money. You pay for outgoing bandwidth on your Cloud Server instance's public IP address, but not on the private one. But, I've also read that it is much faster to use the private IP, or "ServiceNet" as they call it. "Lightning fast" even. So, I tried make a quick-and-dirty benchmark to see for myself.
In short, I don't think it makes much difference, considering the margin of error. Here are the results of a typical test run that shows the timings of uploads of a 1MB file alternating over the public and private interfaces, with a cumulative time printed out at the bottom:
https://gist.github.com/1155335
That example is the most sane run of many test runs I did with this script. What is more disconcerting is that both public and private have wild outliers. Sometimes a transfer that normally takes a tenth of a second can take 30 seconds or even two minutes!
Check out this test run: https://gist.github.com/1155349
Whoa! The 31st upload took 132 seconds! In my experience over multiple runs, the private snet almost always comes out way ahead. It seems like it is just as likely to have 10-second outliers, but less likely to have 30+ second outliers.
If you are interested in reproducing my tests, you can get the code at: https://github.com/scottwb/cloudfiles-snet-bench
On caveat to this test, other than generally not being very scientific, is that I am not using large files (which is the use case I am actually interested in). It is possible that large transfers may get big speed gains over the private servicenet.
Tuesday, August 16, 2011
Rails incorrectly parses HTTP Accept header for single media with range
Try hitting your Rails app with an HTTP header like this:
You will most likely get an exception that looks something like this:
This is because the ActionPack Mime::Type class is buggy in the way it parses this header when there is only one media type specified, and that media type has a range specified (the ";q=0.7"). This is perfectly valid HTML, and ActionPack actually handles the ranges correctly when there are more than one type specified.
An issue has been open for a while on this: https://github.com/rails/rails/issues/736 -- working patches have been proposed but not applied, yet the issue got closed for some reason.
I prefer not to patch my own version of Rails, so instead I am using a small monkey patch that works around this problem. I've created a file named config/initializers/rails_issue_736.rb that fixes the Mime::Type.lookup method to only use the part that comes before the semi-colon:
Accept: text/html;q=0.7
You will most likely get an exception that looks something like this:
Missing template home/index with {:locale=>[:en, :en], :formats=>["text/html;q=0.7"], :handlers=>[:rhtml, :erb, :haml, :rxml, :builder, :rjs]} in view paths "/path/to/my_app/app/views"
This is because the ActionPack Mime::Type class is buggy in the way it parses this header when there is only one media type specified, and that media type has a range specified (the ";q=0.7"). This is perfectly valid HTML, and ActionPack actually handles the ranges correctly when there are more than one type specified.
An issue has been open for a while on this: https://github.com/rails/rails/issues/736 -- working patches have been proposed but not applied, yet the issue got closed for some reason.
I prefer not to patch my own version of Rails, so instead I am using a small monkey patch that works around this problem. I've created a file named config/initializers/rails_issue_736.rb that fixes the Mime::Type.lookup method to only use the part that comes before the semi-colon:
Monday, August 15, 2011
MailMatic: HTML emails using Haml and Sass
Developing static HTML emails is a pain in the butt. For best results, you need to inline all of your styles at HTML attributes instead of using real CSS (externally or inline). You also typically find yourself being very repetitive with your markup if you have a bunch of static emails that share common elements.
MailMatic to the rescue.
MailMatic is a Ruby gem, that is really just a mashup of tools, that aims to ease the burden of creating and maintaining static HTML emails. It uses StaticMatic, Haml, Sass, and Compass to let you author your HTML emails with all of the facilities you enjoy while creating your dynamic site: templates, partials, helper functions, inline Ruby code, reuse of markup and styles, etc. It uses Premailer to convert the HTML/CSS generated from Haml/Sass into self-contained HTML files that inline all of their styles. Premailer even gives you warnings about styles that may not work nicely in certain email readers.
Armed with this, you can accelerate your ability to crank out static HTML emails, and lessen the burden of maintaining them.
To get started with MailMatic, check out its installation and usage instructions on github at: https://github.com/scottwb/mailmatic.
MailMatic to the rescue.
MailMatic is a Ruby gem, that is really just a mashup of tools, that aims to ease the burden of creating and maintaining static HTML emails. It uses StaticMatic, Haml, Sass, and Compass to let you author your HTML emails with all of the facilities you enjoy while creating your dynamic site: templates, partials, helper functions, inline Ruby code, reuse of markup and styles, etc. It uses Premailer to convert the HTML/CSS generated from Haml/Sass into self-contained HTML files that inline all of their styles. Premailer even gives you warnings about styles that may not work nicely in certain email readers.
Armed with this, you can accelerate your ability to crank out static HTML emails, and lessen the burden of maintaining them.
To get started with MailMatic, check out its installation and usage instructions on github at: https://github.com/scottwb/mailmatic.
Tuesday, July 19, 2011
The ask_geo gem: find the time zone for a given latitude and longitude
The Google Maps API has all kinds of great services like geocoding and reverse geocoding, but it lacks an API to determine a timezone from a latitude and longitude. This kind of service would come in handy, for example, when you are picking a point on Earth and scheduling an event there in the point's local time. It could also be useful for automatically determining a website visitor's current local time based on the geolocation obtained from their browser or IP address.
There is a service called GeoNames, which comes close to serving this need. However, its look-ups are based on "closest point of interest", which means that you can get errors when you are near borders, and some locations may not return any results at all.
There is another service called EarthTools which doesn't have this problem, but it only returns the current offset from UTC at that point. That is great if you only care about the current local time, but leaves you stranded if you need to account for Daylight Savings Time on some future or past date.
After a bit of searching, I came across a great free service called AskGeo. AskGeo provides a very simple JSON-over-HTTP API (or XML if you prefer to party like it's 1999). AskGeo uses a real time zone map, so every point on earth returns a result, and returns real Olson IDs for time zones, so you can look up DST transitions, leap seconds, etc.
I gave AskGeo a try and it works great...and it's fast! Since there was no ready-made Ruby gem that provided a client API, I decided to create one.
Introducing the ask_geo gem: https://github.com/scottwb/ask_geo
It can be installed as a ruby gem. See the github page for installation and usage instructions.
Labels:
geolocation,
ruby,
rubygems,
timezone
Sunday, July 10, 2011
Custom RSpec be_square matcher for CarrierWave
It seems to me that when using CarrierWave for image uploads, particularly user avatars, it would be a pretty common thing to generate at least one square-cropped version of the image. CarrierWave ships with some nice custom matchers to test exact dimensions and such, but I found I wanted a way to just test that an image was square.
I did this using by building a custom matcher on top of the ones CarrierWave provides. If you have the conventional spec_helper.rb that requires support/**/*.rb, then you can just drop this somewhere like support/matchers/carrierwave_matchers.rb:
Then, you can use this like:
Labels:
carrierwave,
CI testing,
rspec,
ruby
Tuesday, May 31, 2011
Encrypted Cookie Store that works with Rails 3.0
If you like the benefits using Rails's CookieStore, but want to store possibly sensitive data in the cookie, then encrypted_cookie_store is for you. It works like CookieStore, but encrypts the cookie payload so that it cannot be read by the client.
If you are using Ruby on Rails 3.0.0 or higher (but not yet Rails 3.1), then you'll need my fork of encrypted_cookie_store that fixes it for Rails 3.
To install it:
gem install scottwb-encrypted_cookie_store
Then add to your bundler Gemfile:
gem 'scottwb-encrypted_cookie_store', :require => 'encrypted_cookie_store'
Then read the rest of the installation/configuration instructions.
Background
For Rails 2.3, the folks at Phusion created encrypted_cookie_store, which you'd install as a plugin, and it worked great. I used it for a long time.
However, they never updated it for Rails 3. That's where Ben Sales came in. He forked this project and made it work for Rails 3...in the pre-release days, that is. Ben did all the work to get it packaged up as a gem and updated it to work with Rails 3 railties and initializers.
Unfortunately, sometime between Rails 3.0.0.beta3 and 3.0.0.beta4, the layout of AbstractStore and CookieStore changed quite a bit, pushing a lot of the functionality out to Rack, and breaking the encrypted_cookie_store gem.
That's where I come in. I basically did the minimal amount of work required to get it to work with Rails 3.0 (tested on 3.0.0, 3.0.7, and 3.0.8.rc4), got all the specs working again, and created a new gem called 'scottwb-encrypted_session_cookie'.
It doesn't work in Rails 3.1, but I'll probably remedy that once Rails 3.1 officially releases. I'm also happy to accept patches if anyone else onces to tackle that.
This is a nice gem. Maybe some day I'll make a push to clean it up and lobby to have it as one of the packaged options that ships with Rails...
Wednesday, March 30, 2011
How to delete a remote git tag
I suppose this is probably taboo. You're not supposed to mess with tags once you've pushed them upstream. Still, there are times when it is necessary, and unfortunately `git push --tags` does not push the local removal of tags upstream. It always takes me forever to figure this out, so I figured I'd write it down. Maybe someone else will find it useful.
This will remove that tag from the remote repository. You can verify this by pulling from the remote again and seeing that it does not get pulled back down.
git tag -d tag-to-delete
git push origin :refs/tags/tag-to-delete
This will remove that tag from the remote repository. You can verify this by pulling from the remote again and seeing that it does not get pulled back down.
Thursday, February 10, 2011
Rails-like number_with_delimiter in javascript
The number_with_delimiter view helper is Rails is nice. I wanted to do the same thing in Javascript. I went to just grab it from Rails and port it to js. But first I googled and found someone had already done exactly that. I took his code and made it extend Number.protoype so you can do something like:
This will show that str is "12,345,678".
Her's my version of the code:
Based on code from: http://kevinvaldek.com/number-with-delimiter-in-javascript
var num = 12345678;
var str = num.number_with_delimiter();
alert(str);
This will show that str is "12,345,678".
Her's my version of the code:
Based on code from: http://kevinvaldek.com/number-with-delimiter-in-javascript
Labels:
javascript
Thursday, January 27, 2011
YUI Compressor breaks CSS3 Media Query Syntax
If you use the CSS3 Media Query Syntax for something like this:
You will find that when you compress this with YUI Compressor (as is done when packaging your assets with Jammit), that the output breaks this syntax. YUI Compressor removes the whitespace between the "and" and the opening parenthesis, which does not conform to the CSS3 standard, and renders those styles unusable in most browsers (tested in Chrome and Safari, read about others hitting this in Firefox).
There's a YUI Compressor bug filed here that covers this: http://yuilibrary.com/projects/yuicompressor/ticket/2528053
I am invoking YUI Compressor via an asset-packager called Jammit. In a blog post yesterday, I noted some problems I encountered with Jammit not handling duplicate @charset directives generated by Sass/Compass, and outlined a quick hack workaround I used to deal with it.
Today, encountering this @media-related bug leads to an additional workaround I had to add to that. So, I figured I'd share a bit of my resulting rake task that combines all of these.
Here's the final rake task:
@media screen and (max-device-width: 480px) {
body {font-size: 18px;}
}
You will find that when you compress this with YUI Compressor (as is done when packaging your assets with Jammit), that the output breaks this syntax. YUI Compressor removes the whitespace between the "and" and the opening parenthesis, which does not conform to the CSS3 standard, and renders those styles unusable in most browsers (tested in Chrome and Safari, read about others hitting this in Firefox).
There's a YUI Compressor bug filed here that covers this: http://yuilibrary.com/projects/yuicompressor/ticket/2528053
My Workaround
I am invoking YUI Compressor via an asset-packager called Jammit. In a blog post yesterday, I noted some problems I encountered with Jammit not handling duplicate @charset directives generated by Sass/Compass, and outlined a quick hack workaround I used to deal with it.
Today, encountering this @media-related bug leads to an additional workaround I had to add to that. So, I figured I'd share a bit of my resulting rake task that combines all of these.
- Use compass to compile my Sass to CSS without compressing it (this is important)
- Use sed to remove all @charset directives (dangerous, but I know I don't need them in this case). Take care to make sure the differences in how the -i parameter to sed works between OS X and Linux.
- Use jammit to package up everything.
- For each permutation (e.g.: normal, datauri) CSS package jammit generated, use sed to add the missing space back in to offending @media directives.
- For each of those CSS files we sed-edited, re-gzip them. (Jammit made gzipped versions originally, but we have to regenerate them since we changed the contents.)
Here's the final rake task:
Wednesday, January 26, 2011
Jammit, Compass, and Safari: Can't we all just get along?
When Jammit is used with CSS files generated by Compass, the resulting CSS file may not work with Safari. This is because every Sass file that includes Compass will add the following line to the top of the generated CSS file:
@charset "UTF-8";
That happens because something in Compass requires UTF-8, and Sass will generate that line if anything it is processing requires UTF-8. This is all fine...until you try to combine more than one of these standalone-css files with an asset packager such as Jammit.
Once Jammit combines all these CSS files, you end up with one CSS file that has multiple @charset directives in it, which according to the W3, is a no-no. Generating a CSS file with more than one @charset directive (and anywhere other than the very first line) is clearly against the W3's spec...but the only browser it seems to break is Safari.
But here's the thing: why do my CSS files need to have the @charset added by Sass when they don't actually get output with any non-ASCII characters?
In the end, my quick stop-gap solution was to remove them myself. I used to let Jammit do all the driving. During deployment it would force the regeneration of the CSS files and package them. Now I have to break out the Compass step and add my own sed command in order to remove all the @charset directives:
I think each one of these components has something to improve:
Safari:
If you don't support multiple @charset directives, I support you on that front. The spec says you're right. However...can't you just raise an error that says "ERROR: multiple @charset directives" or something? That would be much better than just randomly disabling half the CSS styles.
Sass:
Sass shouldn't add a @charset line if the generated CSS does not need it. If a mixin that uses UTF-8 is included but not used, and is not represented in the generated CSS, there is no need to add a @charset directive on its behalf.
Compass:
Compass is probably doing nothing wrong here. Though I do question why it needs to use UTF-8 characters. Maybe that's for a feature I haven't used yet.
Jammit:
In the end, I think Jammit is the real culprit here. It takes in N perfectly-valid CSS files and outputs one invalid CSS file. Jammit should remove duplicate @charset directives, and if they are conflicting, it should convert the charset of the conflicting stylesheet and into the charset being used by the output file.
Tuesday, January 25, 2011
Workaround an IE bug: Redirecting subdomains to www while preserving virtual hosts (Nginx, Rails)
I ran into an interesting redirect configuration problem that was exacerbated by Internet Explorer's handing of cookies, which led me to move all subdomain redirection logic out of my Rails app and into Nginx. In the end, this feels like a good thing anyway. If you just want the conclusion, skip to the solution section.
My original setup was to have nginx have virtual hosts for www.example.com, test.example.com, and staging.example.com, where the www.example.com was the default one that would catch anything else such as foo.example.com, or just example.com. Then the Rails app at www.example.com would check the URI in a before_filter and redirect to www.example.com, using a solution similar to the one described here: http://stackoverflow.com/questions/327122/redirect-myapp-com-to-www-myapp-com-in-rails-without-using-htaccess.
Background
My original setup was to have nginx have virtual hosts for www.example.com, test.example.com, and staging.example.com, where the www.example.com was the default one that would catch anything else such as foo.example.com, or just example.com. Then the Rails app at www.example.com would check the URI in a before_filter and redirect to www.example.com, using a solution similar to the one described here: http://stackoverflow.com/questions/327122/redirect-myapp-com-to-www-myapp-com-in-rails-without-using-htaccess.
Problem
The problem arose when an Internet Explorer user hit the site via http://example.com (i.e.: without the "www." prefix). Here is what happens when someone hits example.com in this setup:
- The default virtual host for www.example.com picks up the request and hands it to the Rails app.
- The Rails app's before_filter sees that the request.host does not start with 'www', and does a redirect.
- Somewhere the ActionController internals set a session cookie on the domain "example.com" -- even though this before_filter redirects BEFORE any code tries to touch the session. (Perhaps this is an artifact of using CookieStore.)
- The browser stores the session cookie for example.com, the follows the redirect to www.example.com, sending that cookie (which is basically an empty session at this point).
- The user logs in. The Rails app sets stuff in the session and returns a response that sets the new session cookie with the new session, for www.example.com.
- The browser now has two session cookies: One not-logged-in one for example.com, and one logged-in one for www.example.com.
- The next page load is where the problems start...
On Safari, Chrome, and Firefox, the next page load, on www.example.com, only sends the session cookie that is for www.example.com...and all is well. However, on Internet Explorer (tested on IE8 and IE9 beta), the browser sends BOTH session cookies, which both have the same name. In my observation, Rails always choose the first one, which is always the LEAST specific one - the one for example.com. Now, even though the user just logged in, he is not logged in.
I don't know what the HTTP RFC for user agents says about this, but I am just gonna go ahead and call this in IE bug. According to an MSDN FAQ about IE's cookie-handling, IE is different than other browsers, and they're just fine with that (see Q3 on that page). Also see Q1 where they say they don't even try to support the RFC for cookies.
Similar problems have been documented on the web. I read somewhere that if your Rails app redirects before touching the session, that you won't have this problem. That's not the case for me, but I suspect that may have to do with using CookieStore. I can imagine that CookieStore touches the session by reading it when it comes time to generate the cookie, and that this gets triggered even after a redirect.
Redirect with Nginx
Since I could not get Rails to NOT set a cookie for example.com, I decided I would do this redirect in nginx. There are plenty of examples on the web about redirecting example.com to www.example.com, or vice-versa. However, most of them don't work for my needs for one particular reason: virtual hosts.
In my scenario, I can't redirect ALL requests to non-www subdomains to the www-subdomain, because I have other virtual hosts on specific sub-domains that should not be re-routed. However, I can't simply enumerate the ones that I want redirected, since that is meant to be a catch-all. Rather than try to maintain a regular expression that matches all subdomains except the ones I setup virtual hosts on, I decided to just test the hostname inside the default virtual host, as shown in the conclusion section below. This way, specific subdomains get routed to the right virtual host, anything else gets routed to the www.example.com virtual host, and within that one, anything that isn't www.example.com gets redirected to www.example.com.
Solution
The final solution: this nginx config mockup shows how I can have specific subdomains handled by their virtual hosts, and everything else redirected to the www subdomain.
Using tcpdump to sniff HTTP traffic from a specific host
This is mostly just a reminder to myself about my preferred parameters to tcpdump on linux, so that I don't have to keep reading the man page.
tcpdump -c 20 -s 0 -i eth1 -A host 192.168.1.1 and tcp port http
The parameter breakdown:
- -c 20: Exit after capturing 20 packets.
- -s 0: Don't limit the amount of payload data that is printed out. Print it all.
- -i eth1: Capture packets on interface eth1
- -A: Print packets in ASCII.
- host 192.168.1.1: Only capture packets coming to or from 192.168.1.1.
- and tcp port http: Only capture HTTP packets.
Friday, December 10, 2010
Hate the emacs tilde backup files?
I do...but for decades I have been afraid to turn them off in case I ever needed the backup file, even though I have never used them once. Finally I snapped and tried to figure out how to turn them off. While looking this up, I came across a better option: store them all in a single hidden directory, instead of littering the whole filesystem with them. There is a nice package called "backup-dir" that even provides the ability to keep multiple versions of your backup files, while keeping them all out of sight and out of mind, and automatically cleaning up old versions. Learn more at:
To see how I pulled in the backup-dir package and set it up in my init.el file, see the change to my dotfiles project.
Wednesday, December 8, 2010
Creating/Deleting local and remote branches with git
In the course of my git-based workflow, more often than not, I use branches like this:
- Create a new local branch starting from the HEAD of my current working branch.
- Immediately push it upstream to the remote origin so that it exists in both places.
- Set the local branch to track the remote branch.
- Commit/push/repeat
- Merge the branch back into master (or wherever it started from)
- Delete the local branch.
- Push to delete the remote branch.
- git branch-create feature_branch
- Commit/push/repeat.
- Merge branch back into parent branch.
- git branch-delete feature_branch
To use these scripts via the above commands, download the scripts above and place them somewhere in your path. I even created short aliases for them like so:
Saturday, December 4, 2010
Installing curb gem on Mac OS X 10.6 (Snow Leopard)
If you have previously installed curl with something like:
sudo port install curl +ssl
and then try to install the curb gem like:
sudo gem install curb
and you find yourself getting an error that looks something like this:
In file included from /opt/local/include/curl/curl.h:44,
from curb.h:12,
from curb.c:8:
/opt/local/include/curl/curlrules.h:144: error: size of array ‘__curl_rule_01__’ is negative
/opt/local/include/curl/curlrules.h:154: error: size of array ‘__curl_rule_02__’ is negative
lipo: can't open input file: /var/folders/wX/wX64Cb+PGjG-EXuklO+I+k+++TI/-Tmp-//ccKIrqTY.out (No such file or directory)
make: *** [curb.o] Error 1
Then, I think I have a solution for you. Change your curb install command to this instead:
sudo env ARCHFLAGS="-Os -arch x86_64 -fno-common" gem install curb
It seems a number of people on the web suggest re-installing curl as a universal binary using something like:
sudo port install zlib +universal
sudo port upgrade --enforce-variants openssl +universal
sudo port install curl +universal
I do not like this approach. The original problem is that you installed an x86_64 version of curl (which is the default, as it should be) but you are trying to install a universal version of curb (which is unfortunately the default). Instead of re-installing curl to be universal, which is wasteful and takes forever, install curb using the x86_64 flags to build it. This is what you want, it works, and it only takes a few seconds.
Tuesday, September 21, 2010
Huge speed gain migrating large tables in Rails
Have you ever needed to make multiple column adds/removes/changes to a large table in Rails in a single migration? If so, you've probably noticed that each of these individual changes issues a single ALTER TABLE command to the database, which can take a long time on a large table. At least with MySQL, combining these all into a single ALTER TABLE dramatically reduces the amount of time it takes for your migration to run.
Rather than write custom SQL for this, the folks at XING have created a very cool Rails plugin called alter_table. Their blog post, Alter Table Rails Plugin, gives more background on this. Check it out, it's a good, quick read.
One thing they didn't mention in their post was what kind of performance gains they observed. I was curious, so I did a quick-and-dirty experiment.
Consider an existing table named "songs" that has 330K records in it. First, I tried just adding a column named "foo" using the normal migration style we're all accustomed to:
On my MacBook Pro, this is what the timings for this looked like:
Now, after rolling that back, installing the alter_table plugin (as per their instructions), I rewrote this migration to use the new alter_table method:
Now, on the same machine, this migration takes roughly half the time because it does all the alterations in a single pass. Here are the new timings:
In real life, I had a table with almost 10 million rows that I needed to do 10 alterations to. Using this plugin, I cut my migration time down by almost 10x! If you find yourself doing more than one alteration on the same table in a single migration, I highly recommend checking out alter_table. You can find their source code at:
Subscribe to:
Posts (Atom)
