Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

About this user

Jesse Newland http://jnewland.com

« Newer Snippets
Older Snippets »
Showing 1-9 of 9 total  RSS 

Restore a single table from a large MySQL backup

Say, for some reason, you need to restore the entire contents of a single table from a HUGE mysqldump generated backup containing several tables. For example:

   1  
   2  create table `baz`;
   3  
   4  GIGS OF SQL YOU DON'T WANT;
   5  
   6  create table `foo`;
   7  
   8  A COUPLE THOUSAND LINES YOU DO WANT;
   9  
  10  create table `bar`;
  11  
  12  MORE SQL YOU DON'T WANT;


With a little dash 'o ruby, you can extract just the part you want:

   1  
   2  $ ruby -ne '@found=true if $_ =~ /^CREATE TABLE `foo`/i; next unless @found; exit if $_ =~ /^CREATE TABLE (?!`foo`)/i; puts $_;' giant_sql_dump.sql > foo.sql
   3  $ cat foo.sql
   4  create table `foo`;
   5  
   6  A COUPLE THOUSAND LINES YOU DO WANT;
   7  


You can then easily restore that entire table:

   1  
   2  $ mysql mydatabase -e 'drop table foo'
   3  $ mysql mydatabase < foo.sql

open_body_tag

   1  
   2    #creates a body tag uniquely indentifying this page
   3    #takes an options Hash with two keys:
   4    #
   5    #<tt>id</tt>::        string that will be used as the body's ID. defaults to <tt>controller.controller_name.singularize</tt>
   6    #<tt>classes</tt>::   an Array of class names. defaults to <tt>[params[:action]]</tt>
   7    #
   8    #Examples:
   9    #
  10    # in HomeController#index:
  11    #
  12    # <%= open_body_tag %>
  13    # => <body id='home' class='index'>
  14    #
  15    # <%= open_body_tag(:id => 'foo') %>
  16    # => <body id='foo' class='index'>
  17    #
  18    # <%= open_body_tag(:id => 'foo', :classes => %w(one two)) %>
  19    # => <body id='foo' class='one two'>
  20    def open_body_tag(options = { :id => controller.controller_name.singularize, :classes => [params[:action]] })
  21      "<body id='#{options[:id]}' class='#{options[:classes].join(' ')}'>"
  22    end

Rails URL Validation

No regexes, allows URLs with ports or IPs. Inspiration from here

   1  
   2    validates_each :href, :on => :create do |record, attr, value|
   3      begin
   4        uri = URI.parse(value)
   5        if uri.class != URI::HTTP
   6          record.errors.add(attr, 'Only HTTP protocol addresses can be used')
   7        end
   8      rescue URI::InvalidURIError
   9        record.errors.add(attr, 'The format of the url is not valid.')
  10      end
  11    end

Mofo - Parse Microformats with Ruby

   1  
   2  $ sudo gem install mofo 
   3  Successfully installed mofo-0.2.1
   4  $ irb -rubygems
   5  >> require 'mofo'
   6  => true
   7  >> HResume.find("http://resume.jnewland.com").tags.uniq.sort
   8  => ["AJAX", "Apache", "CSS", "Capistrano", "DNS", "GNU/Linux", "HTML", "Javascript", "LAMP", "Mongrel", "Movable Type", "MySQL", "PHP", "Perl", "REST", "RSS", "Ruby", "Ruby on Rails", "SEO", "XHTML", "XML", "XSLT", "high availability", "lighttpd", "load-balanced"]

RSS Twitter Bot

Republish an RSS feed on a twitter account. This was the source I used to run the Woot Twitter Bot before they took it over.

   1  
   2  require 'rubygems'
   3  require 'active_record'
   4  require 'simple-rss'
   5  require 'open-uri'
   6  require 'twitter'
   7  
   8  #twitter account to post to
   9  twitter_email = "yourtwitteremail@bla.com"
  10  twitter_password = "secret"
  11  
  12  #rss feed to post
  13  rss_url = "http://yoursite.com/index.xml"
  14  rss_user_agent = "http://twitter.com/yourbot"
  15  
  16  #sqlite db
  17  path_to_sqlite_db = "/PATH/TO/db.sqlite"
  18  
  19  
  20  ActiveRecord::Base.logger = Logger.new(STDERR)
  21  ActiveRecord::Base.colorize_logging = false
  22  
  23  ActiveRecord::Base.establish_connection(
  24      :adapter => "sqlite3",
  25      :dbfile  => path_to_sqlite_db
  26  )
  27  
  28  #uncomment this section the first time to create the table
  29  #
  30  #ActiveRecord::Schema.define do
  31  #    create_table :item do |table|
  32  #        table.column :title, :string
  33  #        table.column :link, :string
  34  #    end
  35  #end
  36  
  37  class Item < ActiveRecord::Base
  38    def to_s
  39      "#{self.title[0..(130-self.link.length)]} - #{self.link}"
  40    end
  41  end
  42  
  43  #run the beast
  44  rss_items = SimpleRSS.parse open(rss_url ,"User-Agent" => rss_user_agent)
  45  
  46  for item in rss_items.items
  47    Item.transaction do
  48      unless existing_item = Item.find(:all, :conditions => ["link=?", item.link]).first
  49        twitter ||= Twitter::Base.new(twitter_email, twitter_password)
  50        new_item = Item.create(:title => item.title, :link => item.link) 
  51        twitter.post(new_item.to_s)
  52      end
  53    end
  54  end


Run this once with the lines uncommented to create the DB, then slap it in your crontab.

Ruby One Time Web Server

An interpretation of OneTimeWebServer in Ruby. OneTimeWebServer holds a single "page" in memory, serves it to the first visitor, and evaporates. Useful for all sorts of hijinks.

   1  
   2  #!/usr/local/bin/ruby
   3  require 'socket'
   4  t = STDIN.read
   5  while s = TCPServer.new('127.0.0.1', (ARGV[0] or 8080)).accept
   6    puts s.gets
   7    s.print "HTTP/1.1 200/OK\rContent-type: text/plain\r\n\r\n" + t
   8    s.close
   9    exit
  10  end


Usage:

   1  
   2  echo "test" | ./otws.rb [optional port number, defaults to 8080]


Or for recursive fun:

   1  
   2  cat otws.rb | ./otws.rb [optional port number, defaults to 8080]

Export del.icio.us links to MT Import Format

A friend of mine needed his del.icio.us links in MT Import format for some reason. This solved that problem.

   1  
   2  require 'rexml/document'
   3  require 'net/https'
   4  require 'rubygems'
   5  
   6  # change credentials!
   7  user = 'username'
   8  pass = 'password'
   9  
  10  # User-Agent: required for del.icio.us api
  11  agent = 'delicious-mt'
  12  xml = ''
  13  
  14  http = Net::HTTP.new('api.del.icio.us', 443)
  15  http.use_ssl = true
  16  http.start do |http|
  17    request = Net::HTTP::Get.new('/v1/posts/all', {'User-Agent' => agent})
  18    request.basic_auth(user, pass)
  19    response = http.request(request)
  20    response.value
  21    xml = response.body
  22  end
  23   
  24  REXML::Document.new(xml).elements.each('posts/post') do |el|
  25    puts "TITLE: #{el.attributes['description']}"
  26    puts "AUTHOR: Author Name"
  27    puts "DATE: #{DateTime.parse(el.attributes['time']).strftime("%m/%d/%Y %H:%M:%S")}"
  28    puts "-----"
  29    puts "BODY:"
  30    puts el.attributes['extended']
  31    puts "-----"
  32    puts "EXCERPT:"
  33    puts el.attributes['href']
  34    puts "KEYWORDS:"
  35    puts el.attributes['tag']
  36    puts "-----"
  37    puts "--------"
  38  end

Capistrano : apply local patches when deploying from an external source code repository

I've submitted patches to a couple rails apps, and want to run off of their SCM's trunk code, but with my local patches applied. These Capistrano tasks will take any files matching
patches/*.diff
in your local directory, and apply them before restarting your app.

   1  
   2  task :after_setup do
   3    patches_setup
   4  end
   5  
   6  task :after_update_code do
   7    send_and_apply_patches
   8  end
   9  
  10  task :patches_setup do
  11    run "mkdir -p #{deploy_to}/#{shared_dir}/patches" 
  12  end
  13  
  14  task :send_and_apply_patches do
  15    Dir[File.join(File.dirname(__FILE__), '../patches/*.diff')].sort.each do |patch|
  16      puts "sending #{File.basename(patch)}"
  17      put(File.read(patch),
  18         "#{deploy_to}/#{shared_dir}/patches/#{File.basename(patch)}",
  19         :mode => 0777)
  20      puts "applying #{File.basename(patch)}"
  21      run "cd #{release_path}; patch -p0 < #{deploy_to}/#{shared_dir}/patches/#{File.basename(patch)}"
  22    end
  23  end

redirect or render

Quick method to help your XHR requests degrade gracefully - via the caboo.se

   1  
   2  def redirect_or_render( redirect_to_hash, render_page  )  
   3    if @request.xhr?
   4      render(render_page)
   5    else
   6      redirect_to(redirect_to_hash)
   7    end
   8  end


Use like this:

   1  
   2  redirect_or_render(  
   3    {:action=>'foo'},
   4    { :partial => 'monkey', :locals => { :obj = > 'x' } }
   5  )
« Newer Snippets
Older Snippets »
Showing 1-9 of 9 total  RSS