Life as Clay

Archive for the ‘Ruby’ Category

Paperclip, S3 & Delayed Job in Rails on Heroku – Jan 2012

with 2 comments

Edit: I forgot to mention here that with Paperclip 2.4.5 you have to use the ‘paperclip-aws’ gem in order for Paperclip to work with Amazon’s newer ‘aws-sdk’ gem. That is no longer true with Paperclip 2.5.

I followed this good tutorial on how to push paperclip image processing to the background with delayed_job. My Rails app is deployed to Heroku on the cedar stack. I’ve had problems with the NoMethod errors using delayed_job 3.0.0, so I downgraded to 2.1.4. Also using paperclip version 2.4.5. In the end, I found that I could ditch the struct presented in the aforementioned tutorial and just call handle_asynchronously on my reprocessing method. This is what the codes looks like:


class Image < ActiveRecord::Base
  attr_accessible :profile_pic,
                  :caption,
                  :note,
                  :pic_file_name,
                  :pic_content_type,
                  :pic_file_size,
                  :pic_updated_at,
                  :pic,
                  :pic_attributes,
                  :processing
  
  belongs_to :imageable, :polymorphic => true
  
  # Added for paperclip-aws
  def self.s3_config
      @@s3_config ||= YAML.load(ERB.new(File.read("#{Rails.root}/config/s3.yml")).result)[Rails.env]    
  end
  
  has_attached_file :pic,
                    :styles => { 
                      :large => "500x500>",
                      :thumb => "100x100>", 
                      :tiny => "50>x50>", 
                      :smallest => "24>x24>" },   
                      :default_url => '/:attachment/:style/missing.png',               
                      
                      # Added for paperclip-aws
                      :storage => :aws,
                      :s3_permissions => :authenticated_read,
                      :path => "images/:id/:style/:filename",
                      :s3_credentials => {
                        :access_key_id => self.s3_config['access_key_id'],
                        :secret_access_key => self.s3_config['secret_access_key']
                      },
                      :bucket => self.s3_config['bucket'],
                      :s3_protocol => "https"    
                      
  validates_attachment_content_type :pic, :content_type => [ /^image\/(?:jpeg|gif|png)$/, nil ]
  
  # How to implement on Heroku with processing in the background
  # http://madeofcode.com/posts/42-paperclip-s3-delayed-job-in-rails
  
  # cancel post-processing now, and set flag...
     before_pic_post_process do |image|
       if !image.processing && image.pic_changed?
         image.processing = true
         false # halts processing
       end
     end
     
     # call method from after_save that will be processed in the background
     after_save do |image| 
       if image.processing
         processImageJob(image)
       end
     end
     
     def processImageJob(image)
         image.regenerate_styles!
     end
     handle_asynchronously :processImageJob
     
     # generate styles (downloads original first)
     def regenerate_styles!
       self.pic.reprocess! 
       self.processing = false   
       self.save(:validations => false)
     end
     
     # detect if our source file has changed
     def pic_changed?
       self.pic_file_size_changed? || 
       self.pic_file_name_changed? ||
       self.pic_content_type_changed? || 
       self.pic_updated_at_changed?
     end
                      
end

Advertisements

Written by Clay

January 12, 2012 at 14:29

Posted in Code, Rails, Ruby

Tagged with , , , , ,

Using Colorbox with Rails 3.1

with 2 comments

I’m in the midst of creating a mini-Facebook like Rails app that I can use to track events in my daughter’s life. Part of that includes the ability to attach photos to events. I wanted to use a friendly modal popup for displaying larger versions of photos, so I elected to go with ColorBox. It’s a jQuery plugin that is dead simple to use, especially on static pages.

For the “timeline” page, a dynamic page, I never know whether there will be photos to display and if there are, how they are grouped. The idea is that photos that are attached to the same event should all be part of one gallery.

Here’s what I did…

Anything that can end up on the timeline is a “mark” in my app. I use a partial when iterating through the marks to display photos that may be associated with the mark. Here is that partial:

<% if mark.images.count > 0 %>
	<div class="mark_images">
		<% for image in mark.images %>
				<a href="<%= image.pic(:large) %>" class="gallery_<%= mark.id %>" title="<%= image.caption %>"><%= image_tag(image.pic(:tiny), :title => image.caption, :class => "mark_image") %></a>
		<% end%>
	</div>
<% end %>

As you can see, I’m using thumbnail images as links. The images, by the way, are attached using the Paperclip gem from thoughtbot. The code above sets up the HTML that ColorBox needs in order to display the modal.

The rest of the work comes in javascript. I elected to put the ColorBox javascript at the end of my application.js file. It looks like this:

$(document).ready(function() {
	galleries = [];
	$('a[class^="gallery_"]').each( function() {
		if ($.inArray($(this).attr("class"), galleries) == -1) {
			$(this).colorbox({
				rel: $(this).attr("class"),
				maxWidth: "95%",
				maxHeight: "95%"
			});
			galleries.push($(this).attr("class"));
		}
	});
});

Here I create an empty array called galleries. I then find all link elements on the page that have a class that begins with “gallery_“. I iterate on each of them. If the class of the element is not in the galleries array, then I set up ColorBox for that class (gallery) and I add the class name to the galleries array so that I know not to set it up again.

Finally, I use the class of the gallery to relate the images that share the same class together, so that I get the navigational buttons on the modal viewbox.

To make this all work, you have to drop the ColorBox .js file into your assets/javascripts directory and you need to include both the .css file that you prefer (from the ColorBox downloadable examples) and the images that accompany it. I chose to use example 3. I had to modify the css image paths so that it would locate the ColorBox images in my assets/images directory. I elected to rename the enclosing folder to colorbox_images. The css file I ended up with looks like this:

/*
    ColorBox Core Style:
    The following CSS is consistent between example themes and should not be altered.
*/
#colorbox, #cboxOverlay, #cboxWrapper{position:absolute; top:0; left:0; z-index:9999; overflow:hidden;}
#cboxOverlay{position:fixed; width:100%; height:100%;}
#cboxMiddleLeft, #cboxBottomLeft{clear:left;}
#cboxContent{position:relative;}
#cboxLoadedContent{overflow:auto;}
#cboxTitle{margin:0;}
#cboxLoadingOverlay, #cboxLoadingGraphic{position:absolute; top:0; left:0; width:100%;}
#cboxPrevious, #cboxNext, #cboxClose, #cboxSlideshow{cursor:pointer;}
.cboxPhoto{float:left; margin:auto; border:0; display:block;}
.cboxIframe{width:100%; height:100%; display:block; border:0;}

/*
    User Style:
    Change the following styles to modify the appearance of ColorBox.  They are
    ordered & tabbed in a way that represents the nesting of the generated HTML.
*/
#cboxOverlay{background:#000;}
#colorbox{}
    #cboxContent{margin-top:20px;margin-bottom:20px}
        .cboxIframe{background:#fff;}
        #cboxError{padding:50px; border:1px solid #ccc;}
        #cboxLoadedContent{border:5px solid #000; background:#fff;}
        #cboxTitle{position:absolute; bottom:-15px; left:0; color:#ccc;}
        #cboxCurrent{position:absolute; top:-20px; right:0px; color:#ccc;}
        #cboxSlideshow{position:absolute; top:-20px; right:90px; color:#fff;}
        #cboxPrevious{position:absolute; top:50%; left:5px; margin-top:-32px; background:url(/assets/colorbox_images/controls.png) no-repeat top left; width:28px; height:65px; text-indent:-9999px;}
        #cboxPrevious:hover{background-position:bottom left;}
        #cboxNext{position:absolute; top:50%; right:5px; margin-top:-32px; background:url(/assets/colorbox_images/controls.png) no-repeat top right; width:28px; height:65px; text-indent:-9999px;}
        #cboxNext:hover{background-position:bottom right;}
        #cboxLoadingOverlay{background:#000;}
        #cboxLoadingGraphic{background:url(/assets/colorbox_images/loading.gif) no-repeat center center;}
        #cboxClose{position:absolute; top:5px; right:5px; display:block; background:url(/assets/colorbox_images/controls.png) no-repeat top center; width:38px; height:19px; text-indent:-9999px;}
        #cboxClose:hover{background-position:bottom center;}

I also chose to move the title to the bottom of the image because that way, it doesn’t bump up against the image count when viewed on a mobile device. That required setting a bottom margin for #cboxContent and changing this line: #cboxTitle{position:absolute; bottom:-15px; left:0; color:#ccc;}.

There are a variety of other options that can be used with the javascript call to alter the modal dialogue. It’s worth taking a look at the ColorBox page for some examples.

Overall, I’m really happy with this solution and probably will use it again in the future. If you’re interested in the app that I’m developing, you can find it on github, called Blytheline. It’s an early work in progress, so it’s a bit rough around the edges!

Written by Clay

November 29, 2011 at 12:53

Ruby snipped to return elapsed time as text

leave a comment »

I sometimes put code on the blog here that i want to be able to locate later. Here’s a bit of that. I use this (mainly with the “text” parameter) to return in text the time elapsed between a start_time DateTime stamp and an end_time DateTime stamp. It’s not perfect, but works well enough for my needs:

 

def duration(display)
    if start_time.nil? || end_time.nil? || start_time.blank? || end_time.blank?
      return ""
    end
    
    seconds = end_time - start_time
    minutes = seconds.to_i / 60
    hours = minutes.to_i / 60
    days = hours.to_i / 24
    
    new_hours = hours - (days * 24)
    new_minutes = minutes - (hours * 60)
    
    case display
      when "minutes"
        return new_minutes
      when "minutes_total"
        return minutes
      when "hours"
        return new_hours
      when "hours_total"
        return hours
      when "days"
        return days
      when "text"
        the_string = ""
    
        if days == 1
          the_string += "1 day "
        elsif days > 0
          the_string += days.to_s + " days "
        end
    
        if new_hours == 1
          the_string += "1 hour "
        elsif new_hours > 0
          the_string += new_hours.to_s + " hours "
        end 
    
        if new_minutes == 1
          the_string += "1 minute "
        else
          the_string += new_minutes.to_s + " minutes"
        end
    
        return the_string
      when "text_short"
        the_string = ""
    
        if days == 1
          the_string += "1 d "
        elsif days > 0
          the_string += days.to_s + " d "
        end
    
        if new_hours == 1
          the_string += "1 h "
        elsif new_hours > 0
          the_string += new_hours.to_s + " h "
        end 
    
        if new_minutes == 1
          the_string += "1 m "
        else
          the_string += new_minutes.to_s + " m"
        end
    end
    
  end

Written by Clay

November 16, 2011 at 12:32

Posted in Code, Ruby

Tagged with

Returning / Dragging Myself to Rails 3.1

leave a comment »

I’ve been away for a few months, on paternity leave. It was a delight. It now is my turn to return to work and pick up where I left off. You probably know that I work with Rails sometimes if you read this blog. The last time I built a large Rails app was just prior to the 3.0 release. I return to find 3.1 on rc5 and I decided it would be a good idea to get up to speed with it.

Rails 3.1 is a huge departure from Rails 2.x. I feel lost — almost as if I have to learn an entirely new framework! Between updating gems, rails, rack, etc., I decided that I had better start with a new gemset. After stumbling through an RVM upgrade last night (stumbling because I allowed too many versions to pass in-between and the upgrade was far from smooth), I installed 3.1.0.rc5 and started a test app. I ran into a few bugs related to the rc status of the release. The first is that I was receiving a JSON error on a vanilla blank app. If you bump into that, just require these gems:

gem 'multi_json'
gem 'json'

The second is that there was a problem with the arel version. Including the following in the Gemfile fixed the issue for the time being:

gem 'arel', '2.1.4' # remove when 3.1.0 is released

The app boots without errors now, so I’m off to plug away at the new Asset Pipeline and other features. If you’re starting fresh with Rails 3.1, check out this page at Github for a great tutorial on how to get started.

Before I go, however, I want to point to a lovely bit of Processing work by Justin Livi. He created a sketch that randomly generates dandelions like the one below. Check out his site to see the interactive applet.

Written by Clay

August 11, 2011 at 08:34

Posted in Rails

Tagged with ,

Parsing US Census data with Ruby

leave a comment »

I am a fan of population pyramids as a visualization of age demographics. They are simple and effective. Sometimes getting the data to generate them isn’t….

I’m building a simple Rails app for a client who needs county-level population data. It doesn’t have to be precise. I went with the 2009 estimates from the Census bureau, located here:
http://www.census.gov/popest/counties/asrh/CC-EST2009-alldata.html

There were a few issues:
1. Each state’s county-level data is in a different file. You can order a CD that has all of the data in a single file, but I didn’t have time to do that.
2. There’s a ton of data that I didn’t need in each file. All I needed were the county totals and the totals for male/female for each age group.
3. The data is in rows — a different row for each age group. I needed the data in columns, with one row for each county.

What I did:
1. Downloaded all 51 of the files (DC has its own file) and put them in a folder on my desktop.
2. Changed the extension on them to .csv (because it changed to .txt when I downloaded, for some reason).
3. Wrote the Ruby script below, which extracts the data that I need and puts it into a single .csv file.
4. Saved the script to the same folder as the Census files as script.rb.
5. Opened terminal and ran ruby script.rb
4. Reconciled the data with my Excel sheet that I was using to collect county-level data so that I could seed my Rails app’s counties table.

I comment my code pretty heavily when I write it so that I can look back and remember what I did. I’ve been burned in the past by not commenting thoroughly.

Here’s the script:

# Script to pull population data out of census files for each county
# Original data files are here: http://www.census.gov/popest/counties/asrh/CC-EST2009-alldata.html

require 'CSV'

# These are the FIPS codes for each state which are used in file names.
state_fips_codes = ["01", "02", "04", "05", "06", "08", "09", "10", "11", "12", "13", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "40", "41", "42", "44", "45", "46", "47", "48", "49", "50", "51", "53", "54", "55", "56"]

add_header = true

# This is the file that all of the data will go into...
File.open("county_age_data.csv", "w") do |output_file|
  
  # counter for iterating through the files
  n = 0
  
  state_fips_codes.length.times do  # This loop goes through all of the files
    
    # Read in the relevant file
    state_data = CSV.parse(File.read("cc-est2009-alldata-" + state_fips_codes[n] + ".csv"))
    puts "Processing data for " + state_data[1][3]

    # Add the header to the file
    if add_header == true
      output_file.puts "state_fips,county_fips,state_name,county_name,:census_total_pop,:census_total_male,:census_grp01_male,:census_grp02_male,:census_grp03_male,:census_grp04_male,:census_grp05_male,:census_grp06_male,:census_grp07_male,:census_grp08_male,:census_grp09_male,:census_grp10_male,:census_grp11_male,:census_grp12_male,:census_grp13_male,:census_grp14_male,:census_grp15_male,:census_grp16_male,:census_grp17_male,:census_grp18_male,:census_total_female,:census_grp01_female,:census_grp02_female,:census_grp03_female,:census_grp04_female,:census_grp05_female,:census_grp06_female,:census_grp07_female,:census_grp08_female,:census_grp09_female,:census_grp10_female,:census_grp11_female,:census_grp12_female,:census_grp13_female,:census_grp14_female,:census_grp15_female,:census_grp16_female,:census_grp17_female,:census_grp18_female"
      add_header = false
    end

    # Iterate through the loaded file.
    row = 1
    while row < state_data.length
      if state_data[row][5].to_i == 12 # Only take data from year coded 12 (2009 estimates)

        ########## MAIN LOGIC #############
        if state_data[row][6].to_i == 0 # It's a new county because this is the group 0 row with totals

          # Reset the data arrays
          row_data    = []
          male_data   = []
          female_data = []

          row_data.push state_data[row][1].to_s     # state_fips
          row_data.push state_data[row][2].to_s     # county_fips
          row_data.push state_data[row][3].to_s     # state_name
          row_data.push state_data[row][4].to_s     # county_name
          row_data.push state_data[row][7].to_s     # census_total_pop

          male_data.push state_data[row][8].to_s    # census_total_male
          female_data.push state_data[row][9].to_s  # census_total_female

        elsif state_data[row][6].to_i == 18 # It's the last row -- push the data into the array

          # push in the final data points
          male_data.push state_data[row][8].to_s    # census_grp18_male
          female_data.push state_data[row][9].to_s  # census_grp18_female

          # append all of the data to the row_data array
          row_data += male_data
          row_data += female_data

          # write the data to the file
          output_file.puts row_data.join(",")

        else # It's not the first or last row

          male_data.push state_data[row][8].to_s    # census_grpXX_male
          female_data.push state_data[row][9].to_s  # census_grpXX_female

        end # End of the if statement for pushing data into arrays
        ################ END OF MAIN LOGIC ####################
        
      end       # End of the if statement to check if it is year 10
      
      row += 1  # Look at the next row
    end

    n += 1      # Increment the counter
  end           # End of loop for going through each file
end

Written by Clay

July 15, 2010 at 21:17

Posted in Code, Ruby

Tagged with , , ,

Resource: Rails country seeds with ISO codes

leave a comment »

In case you need to seed your Rails app with countries. You can use the ISO codes to display flag icons, like these linked ones from famfamfam.com: link.

 countries = Country.create([
                               {:name => 'Åland Islands', :iso_code => 'AX'},
                               {:name => 'Albania', :iso_code => 'AL'},
                               {:name => 'Algeria', :iso_code => 'DZ'},
                               {:name => 'American Samoa', :iso_code => 'AS'},
                               {:name => 'Andorra', :iso_code => 'AD'},
                               {:name => 'Angola', :iso_code => 'AO'},
                               {:name => 'Anguilla', :iso_code => 'AI'},
                               {:name => 'Antarctica', :iso_code => 'AQ'},
                               {:name => 'Antigua and Barbuda', :iso_code => 'AG'},
                               {:name => 'Argentina', :iso_code => 'AR'},
                               {:name => 'Armenia', :iso_code => 'AM'},
                               {:name => 'Aruba', :iso_code => 'AW'},
                               {:name => 'Australia', :iso_code => 'AU'},
                               {:name => 'Austria', :iso_code => 'AT'},
                               {:name => 'Azerbaijan', :iso_code => 'AZ'},
                               {:name => 'Bahamas', :iso_code => 'BS'},
                               {:name => 'Bahrain', :iso_code => 'BH'},
                               {:name => 'Bangladesh', :iso_code => 'BD'},
                               {:name => 'Barbados', :iso_code => 'BB'},
                               {:name => 'Belarus', :iso_code => 'BY'},
                               {:name => 'Belgium', :iso_code => 'BE'},
                               {:name => 'Belize', :iso_code => 'BZ'},
                               {:name => 'Benin', :iso_code => 'BJ'},
                               {:name => 'Bermuda', :iso_code => 'BM'},
                               {:name => 'Bhutan', :iso_code => 'BT'},
                               {:name => 'Bolivia', :iso_code => 'BO'},
                               {:name => 'Bosnia and Herzegovina', :iso_code => 'BA'},
                               {:name => 'Botswana', :iso_code => 'BW'},
                               {:name => 'Bouvet Island', :iso_code => 'BV'},
                               {:name => 'Brazil', :iso_code => 'BR'},
                               {:name => 'British Indian Ocean Territory', :iso_code => 'IO'},
                               {:name => 'Brunei Darussalam', :iso_code => 'BN'},
                               {:name => 'Bulgaria', :iso_code => 'BG'},
                               {:name => 'Burkina Faso', :iso_code => 'BF'},
                               {:name => 'Burundi', :iso_code => 'BI'},
                               {:name => 'Cambodia', :iso_code => 'KH'},
                               {:name => 'Cameroon', :iso_code => 'CM'},
                               {:name => 'Canada', :iso_code => 'CA'},
                               {:name => 'Cape Verde', :iso_code => 'CV'},
                               {:name => 'Cayman Islands', :iso_code => 'KY'},
                               {:name => 'Central African Republic', :iso_code => 'CF'},
                               {:name => 'Chad', :iso_code => 'TD'},
                               {:name => 'Chile', :iso_code => 'CL'},
                               {:name => 'China', :iso_code => 'CN'},
                               {:name => 'Christmas Island', :iso_code => 'CX'},
                               {:name => 'Cocos (Keeling) Islands', :iso_code => 'CC'},
                               {:name => 'Colombia', :iso_code => 'CO'},
                               {:name => 'Comoros', :iso_code => 'KM'},
                               {:name => 'Congo', :iso_code => 'CG'},
                               {:name => 'Congo, The Democratic Republic of The', :iso_code => 'CD'},
                               {:name => 'Cook Islands', :iso_code => 'CK'},
                               {:name => 'Costa Rica', :iso_code => 'CR'},
                               {:name => 'Côte D\'Ivoire', :iso_code => 'CI'},
                               {:name => 'Croatia', :iso_code => 'HR'},
                               {:name => 'Cuba', :iso_code => 'CU'},
                               {:name => 'Cyprus', :iso_code => 'CY'},
                               {:name => 'Czech Republic', :iso_code => 'CZ'},
                               {:name => 'Denmark', :iso_code => 'DK'},
                               {:name => 'Djibouti', :iso_code => 'DJ'},
                               {:name => 'Dominica', :iso_code => 'DM'},
                               {:name => 'Dominican Republic', :iso_code => 'DO'},
                               {:name => 'Ecuador', :iso_code => 'EC'},
                               {:name => 'Egypt', :iso_code => 'EG'},
                               {:name => 'El Salvador', :iso_code => 'SV'},
                               {:name => 'Equatorial Guinea', :iso_code => 'GQ'},
                               {:name => 'Eritrea', :iso_code => 'ER'},
                               {:name => 'Estonia', :iso_code => 'EE'},
                               {:name => 'Ethiopia', :iso_code => 'ET'},
                               {:name => 'Falkland Islands (Malvinas)', :iso_code => 'FK'},
                               {:name => 'Faroe Islands', :iso_code => 'FO'},
                               {:name => 'Fiji', :iso_code => 'FJ'},
                               {:name => 'Finland', :iso_code => 'FI'},
                               {:name => 'France', :iso_code => 'FR'},
                               {:name => 'French Guiana', :iso_code => 'GF'},
                               {:name => 'French Polynesia', :iso_code => 'PF'},
                               {:name => 'French Southern Territories', :iso_code => 'TF'},
                               {:name => 'Gabon', :iso_code => 'GA'},
                               {:name => 'Gambia', :iso_code => 'GM'},
                               {:name => 'Georgia', :iso_code => 'GE'},
                               {:name => 'Germany', :iso_code => 'DE'},
                               {:name => 'Ghana', :iso_code => 'GH'},
                               {:name => 'Gibraltar', :iso_code => 'GI'},
                               {:name => 'Greece', :iso_code => 'GR'},
                               {:name => 'Greenland', :iso_code => 'GL'},
                               {:name => 'Grenada', :iso_code => 'GD'},
                               {:name => 'Guadeloupe', :iso_code => 'GP'},
                               {:name => 'Guam', :iso_code => 'GU'},
                               {:name => 'Guatemala', :iso_code => 'GT'},
                               {:name => 'Guernsey', :iso_code => 'GG'},
                               {:name => 'Guinea', :iso_code => 'GN'},
                               {:name => 'Guinea-Bissau', :iso_code => 'GW'},
                               {:name => 'Guyana', :iso_code => 'GY'},
                               {:name => 'Haiti', :iso_code => 'HT'},
                               {:name => 'Heard Island and Mcdonald Islands', :iso_code => 'HM'},
                               {:name => 'Holy See (Vatican City State)', :iso_code => 'VA'},
                               {:name => 'Honduras', :iso_code => 'HN'},
                               {:name => 'Hong Kong', :iso_code => 'HK'},
                               {:name => 'Hungary', :iso_code => 'HU'},
                               {:name => 'Iceland', :iso_code => 'IS'},
                               {:name => 'India', :iso_code => 'IN'},
                               {:name => 'Indonesia', :iso_code => 'ID'},
                               {:name => 'Iran, Islamic Republic of', :iso_code => 'IR'},
                               {:name => 'Iraq', :iso_code => 'IQ'},
                               {:name => 'Ireland', :iso_code => 'IE'},
                               {:name => 'Isle of Man', :iso_code => 'IM'},
                               {:name => 'Israel', :iso_code => 'IL'},
                               {:name => 'Italy', :iso_code => 'IT'},
                               {:name => 'Jamaica', :iso_code => 'JM'},
                               {:name => 'Japan', :iso_code => 'JP'},
                               {:name => 'Jersey', :iso_code => 'JE'},
                               {:name => 'Jordan', :iso_code => 'JO'},
                               {:name => 'Kazakhstan', :iso_code => 'KZ'},
                               {:name => 'Kenya', :iso_code => 'KE'},
                               {:name => 'Kiribati', :iso_code => 'KI'},
                               {:name => 'Korea, Democratic People\'s Republic of', :iso_code => 'KP'},
                               {:name => 'Korea, Republic of', :iso_code => 'KR'},
                               {:name => 'Kuwait', :iso_code => 'KW'},
                               {:name => 'Kyrgyzstan', :iso_code => 'KG'},
                               {:name => 'Lao People\'s Democratic Republic', :iso_code => 'LA'},
                               {:name => 'Latvia', :iso_code => 'LV'},
                               {:name => 'Lebanon', :iso_code => 'LB'},
                               {:name => 'Lesotho', :iso_code => 'LS'},
                               {:name => 'Liberia', :iso_code => 'LR'},
                               {:name => 'Libyan Arab Jamahiriya', :iso_code => 'LY'},
                               {:name => 'Liechtenstein', :iso_code => 'LI'},
                               {:name => 'Lithuania', :iso_code => 'LT'},
                               {:name => 'Luxembourg', :iso_code => 'LU'},
                               {:name => 'Macao', :iso_code => 'MO'},
                               {:name => 'Macedonia, The Former Yugoslav Republic of', :iso_code => 'MK'},
                               {:name => 'Madagascar', :iso_code => 'MG'},
                               {:name => 'Malawi', :iso_code => 'MW'},
                               {:name => 'Malaysia', :iso_code => 'MY'},
                               {:name => 'Maldives', :iso_code => 'MV'},
                               {:name => 'Mali', :iso_code => 'ML'},
                               {:name => 'Malta', :iso_code => 'MT'},
                               {:name => 'Marshall Islands', :iso_code => 'MH'},
                               {:name => 'Martinique', :iso_code => 'MQ'},
                               {:name => 'Mauritania', :iso_code => 'MR'},
                               {:name => 'Mauritius', :iso_code => 'MU'},
                               {:name => 'Mayotte', :iso_code => 'YT'},
                               {:name => 'Mexico', :iso_code => 'MX'},
                               {:name => 'Micronesia, Federated States of', :iso_code => 'FM'},
                               {:name => 'Moldova, Republic of', :iso_code => 'MD'},
                               {:name => 'Monaco', :iso_code => 'MC'},
                               {:name => 'Mongolia', :iso_code => 'MN'},
                               {:name => 'Montenegro', :iso_code => 'ME'},
                               {:name => 'Montserrat', :iso_code => 'MS'},
                               {:name => 'Morocco', :iso_code => 'MA'},
                               {:name => 'Mozambique', :iso_code => 'MZ'},
                               {:name => 'Myanmar', :iso_code => 'MM'},
                               {:name => 'Namibia', :iso_code => 'NA'},
                               {:name => 'Nauru', :iso_code => 'NR'},
                               {:name => 'Nepal', :iso_code => 'NP'},
                               {:name => 'Netherlands', :iso_code => 'NL'},
                               {:name => 'Netherlands Antilles', :iso_code => 'AN'},
                               {:name => 'New Caledonia', :iso_code => 'NC'},
                               {:name => 'New Zealand', :iso_code => 'NZ'},
                               {:name => 'Nicaragua', :iso_code => 'NI'},
                               {:name => 'Niger', :iso_code => 'NE'},
                               {:name => 'Nigeria', :iso_code => 'NG'},
                               {:name => 'Niue', :iso_code => 'NU'},
                               {:name => 'Norfolk Island', :iso_code => 'NF'},
                               {:name => 'Northern Mariana Islands', :iso_code => 'MP'},
                               {:name => 'Norway', :iso_code => 'NO'},
                               {:name => 'Oman', :iso_code => 'OM'},
                               {:name => 'Pakistan', :iso_code => 'PK'},
                               {:name => 'Palau', :iso_code => 'PW'},
                               {:name => 'Palestinian Territory, Occupied', :iso_code => 'PS'},
                               {:name => 'Panama', :iso_code => 'PA'},
                               {:name => 'Papua New Guinea', :iso_code => 'PG'},
                               {:name => 'Paraguay', :iso_code => 'PY'},
                               {:name => 'Peru', :iso_code => 'PE'},
                               {:name => 'Philippines', :iso_code => 'PH'},
                               {:name => 'Pitcairn', :iso_code => 'PN'},
                               {:name => 'Poland', :iso_code => 'PL'},
                               {:name => 'Portugal', :iso_code => 'PT'},
                               {:name => 'Puerto Rico', :iso_code => 'PR'},
                               {:name => 'Qatar', :iso_code => 'QA'},
                               {:name => 'Réunion', :iso_code => 'RE'},
                               {:name => 'Romania', :iso_code => 'RO'},
                               {:name => 'Russian Federation', :iso_code => 'RU'},
                               {:name => 'Rwanda', :iso_code => 'RW'},
                               {:name => 'Saint Barthélemy', :iso_code => 'BL'},
                               {:name => 'Saint Helena, Ascension and Tristan Da Cunha', :iso_code => 'SH'},
                               {:name => 'Saint Kitts and Nevis', :iso_code => 'KN'},
                               {:name => 'Saint Lucia', :iso_code => 'LC'},
                               {:name => 'Saint Martin', :iso_code => 'MF'},
                               {:name => 'Saint Pierre and Miquelon', :iso_code => 'PM'},
                               {:name => 'Saint Vincent and The Grenadines', :iso_code => 'VC'},
                               {:name => 'Samoa', :iso_code => 'WS'},
                               {:name => 'San Marino', :iso_code => 'SM'},
                               {:name => 'Sao Tome and Principe', :iso_code => 'ST'},
                               {:name => 'Saudi Arabia', :iso_code => 'SA'},
                               {:name => 'Senegal', :iso_code => 'SN'},
                               {:name => 'Serbia', :iso_code => 'RS'},
                               {:name => 'Seychelles', :iso_code => 'SC'},
                               {:name => 'Sierra Leone', :iso_code => 'SL'},
                               {:name => 'Singapore', :iso_code => 'SG'},
                               {:name => 'Slovakia', :iso_code => 'SK'},
                               {:name => 'Slovenia', :iso_code => 'SI'},
                               {:name => 'Solomon Islands', :iso_code => 'SB'},
                               {:name => 'Somalia', :iso_code => 'SO'},
                               {:name => 'South Africa', :iso_code => 'ZA'},
                               {:name => 'South Georgia and The South Sandwich Islands', :iso_code => 'GS'},
                               {:name => 'Spain', :iso_code => 'ES'},
                               {:name => 'Sri Lanka', :iso_code => 'LK'},
                               {:name => 'Sudan', :iso_code => 'SD'},
                               {:name => 'Suriname', :iso_code => 'SR'},
                               {:name => 'Svalbard and Jan Mayen', :iso_code => 'SJ'},
                               {:name => 'Swaziland', :iso_code => 'SZ'},
                               {:name => 'Sweden', :iso_code => 'SE'},
                               {:name => 'Switzerland', :iso_code => 'CH'},
                               {:name => 'Syrian Arab Republic', :iso_code => 'SY'},
                               {:name => 'Taiwan, Province of China', :iso_code => 'TW'},
                               {:name => 'Tajikistan', :iso_code => 'TJ'},
                               {:name => 'Tanzania, United Republic of', :iso_code => 'TZ'},
                               {:name => 'Thailand', :iso_code => 'TH'},
                               {:name => 'Timor-Leste', :iso_code => 'TL'},
                               {:name => 'Togo', :iso_code => 'TG'},
                               {:name => 'Tokelau', :iso_code => 'TK'},
                               {:name => 'Tonga', :iso_code => 'TO'},
                               {:name => 'Trinidad and Tobago', :iso_code => 'TT'},
                               {:name => 'Tunisia', :iso_code => 'TN'},
                               {:name => 'Turkey', :iso_code => 'TR'},
                               {:name => 'Turkmenistan', :iso_code => 'TM'},
                               {:name => 'Turks and Caicos Islands', :iso_code => 'TC'},
                               {:name => 'Tuvalu', :iso_code => 'TV'},
                               {:name => 'Uganda', :iso_code => 'UG'},
                               {:name => 'Ukraine', :iso_code => 'UA'},
                               {:name => 'United Arab Emirates', :iso_code => 'AE'},
                               {:name => 'United Kingdom', :iso_code => 'GB'},
                               {:name => 'United States', :iso_code => 'US'},
                               {:name => 'United States Minor Outlying Islands', :iso_code => 'UM'},
                               {:name => 'Uruguay', :iso_code => 'UY'},
                               {:name => 'Uzbekistan', :iso_code => 'UZ'},
                               {:name => 'Vanuatu', :iso_code => 'VU'},
                               {:name => 'Venezuela, Bolivarian Republic of', :iso_code => 'VE'},
                               {:name => 'Viet Nam', :iso_code => 'VN'},
                               {:name => 'Virgin Islands, British', :iso_code => 'VG'},
                               {:name => 'Virgin Islands, U.S.', :iso_code => 'VI'},
                               {:name => 'Wallis and Futuna', :iso_code => 'WF'},
                               {:name => 'Western Sahara', :iso_code => 'EH'},
                               {:name => 'Yemen', :iso_code => 'YE'},
                               {:name => 'Zambia', :iso_code => 'ZM'},
                               {:name => 'Zimbabwe', :iso_code => 'ZW'}
 ])

Written by Clay

July 13, 2010 at 17:54

Posted in Code, Resource, Ruby

Tagged with , , ,

Resource: Rails database seeds for US States, including ANSI codes

with one comment

In case you need to add US States to your Rails app. The data are from the US Census website. I’m not sure what the purpose of the “Geographic Names Information System Identifier (GNISID)” is (the number after the State name), but it’s included here in case you need to tie back to the census system.

states = State.create([
                        { :name => 'Alabama', :abbr => 'AL', :ansi_code => '1', :statens => '1779775'},
                        { :name => 'Alaska', :abbr => 'AK', :ansi_code => '2', :statens => '1785533'},
                        { :name => 'Arizona', :abbr => 'AZ', :ansi_code => '4', :statens => '1779777'},
                        { :name => 'Arkansas', :abbr => 'AR', :ansi_code => '5', :statens => '68085'},
                        { :name => 'California', :abbr => 'CA', :ansi_code => '6', :statens => '1779778'},
                        { :name => 'Colorado', :abbr => 'CO', :ansi_code => '8', :statens => '1779779'},
                        { :name => 'Connecticut', :abbr => 'CT', :ansi_code => '9', :statens => '1779780'},
                        { :name => 'Delaware', :abbr => 'DE', :ansi_code => '10', :statens => '1779781'},
                        { :name => 'District of Columbia', :abbr => 'DC', :ansi_code => '11', :statens => '1702382'},
                        { :name => 'Florida', :abbr => 'FL', :ansi_code => '12', :statens => '294478'},
                        { :name => 'Georgia', :abbr => 'GA', :ansi_code => '13', :statens => '1705317'},
                        { :name => 'Hawaii', :abbr => 'HI', :ansi_code => '15', :statens => '1779782'},
                        { :name => 'Idaho', :abbr => 'ID', :ansi_code => '16', :statens => '1779783'},
                        { :name => 'Illinois', :abbr => 'IL', :ansi_code => '17', :statens => '1779784'},
                        { :name => 'Indiana', :abbr => 'IN', :ansi_code => '18', :statens => '448508'},
                        { :name => 'Iowa', :abbr => 'IA', :ansi_code => '19', :statens => '1779785'},
                        { :name => 'Kansas', :abbr => 'KS', :ansi_code => '20', :statens => '481813'},
                        { :name => 'Kentucky', :abbr => 'KY', :ansi_code => '21', :statens => '1779786'},
                        { :name => 'Louisiana', :abbr => 'LA', :ansi_code => '22', :statens => '1629543'},
                        { :name => 'Maine', :abbr => 'ME', :ansi_code => '23', :statens => '1779787'},
                        { :name => 'Maryland', :abbr => 'MD', :ansi_code => '24', :statens => '1714934'},
                        { :name => 'Massachusetts', :abbr => 'MA', :ansi_code => '25', :statens => '606926'},
                        { :name => 'Michigan', :abbr => 'MI', :ansi_code => '26', :statens => '1779789'},
                        { :name => 'Minnesota', :abbr => 'MN', :ansi_code => '27', :statens => '662849'},
                        { :name => 'Mississippi', :abbr => 'MS', :ansi_code => '28', :statens => '1779790'},
                        { :name => 'Missouri', :abbr => 'MO', :ansi_code => '29', :statens => '1779791'},
                        { :name => 'Montana', :abbr => 'MT', :ansi_code => '30', :statens => '767982'},
                        { :name => 'Nebraska', :abbr => 'NE', :ansi_code => '31', :statens => '1779792'},
                        { :name => 'Nevada', :abbr => 'NV', :ansi_code => '32', :statens => '1779793'},
                        { :name => 'New Hampshire', :abbr => 'NH', :ansi_code => '33', :statens => '1779794'},
                        { :name => 'New Jersey', :abbr => 'NJ', :ansi_code => '34', :statens => '1779795'},
                        { :name => 'New Mexico', :abbr => 'NM', :ansi_code => '35', :statens => '897535'},
                        { :name => 'New York', :abbr => 'NY', :ansi_code => '36', :statens => '1779796'},
                        { :name => 'North Carolina', :abbr => 'NC', :ansi_code => '37', :statens => '1027616'},
                        { :name => 'North Dakota', :abbr => 'ND', :ansi_code => '38', :statens => '1779797'},
                        { :name => 'Ohio', :abbr => 'OH', :ansi_code => '39', :statens => '1085497'},
                        { :name => 'Oklahoma', :abbr => 'OK', :ansi_code => '40', :statens => '1102857'},
                        { :name => 'Oregon', :abbr => 'OR', :ansi_code => '41', :statens => '1155107'},
                        { :name => 'Pennsylvania', :abbr => 'PA', :ansi_code => '42', :statens => '1779798'},
                        { :name => 'Rhode Island', :abbr => 'RI', :ansi_code => '44', :statens => '1219835'},
                        { :name => 'South Carolina', :abbr => 'SC', :ansi_code => '45', :statens => '1779799'},
                        { :name => 'South Dakota', :abbr => 'SD', :ansi_code => '46', :statens => '1785534'},
                        { :name => 'Tennessee', :abbr => 'TN', :ansi_code => '47', :statens => '1325873'},
                        { :name => 'Texas', :abbr => 'TX', :ansi_code => '48', :statens => '1779801'},
                        { :name => 'Utah', :abbr => 'UT', :ansi_code => '49', :statens => '1455989'},
                        { :name => 'Vermont', :abbr => 'VT', :ansi_code => '50', :statens => '1779802'},
                        { :name => 'Virginia', :abbr => 'VA', :ansi_code => '51', :statens => '1779803'},
                        { :name => 'Washington', :abbr => 'WA', :ansi_code => '53', :statens => '1779804'},
                        { :name => 'West Virginia', :abbr => 'WV', :ansi_code => '54', :statens => '1779805'},
                        { :name => 'Wisconsin', :abbr => 'WI', :ansi_code => '55', :statens => '1779806'},
                        { :name => 'Wyoming', :abbr => 'WY', :ansi_code => '56', :statens => '1779807'}
])

Written by Clay

July 13, 2010 at 17:49

Posted in Code, Resource, Ruby

Tagged with , , ,