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:

create table `baz`;

GIGS OF SQL YOU DON'T WANT;

create table `foo`;

A COUPLE THOUSAND LINES YOU DO WANT;

create table `bar`;

MORE SQL YOU DON'T WANT;


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

$ 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
$ cat foo.sql
create table `foo`;

A COUPLE THOUSAND LINES YOU DO WANT;



You can then easily restore that entire table:

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

open_body_tag

  #creates a body tag uniquely indentifying this page
  #takes an options Hash with two keys:
  #
  #<tt>id</tt>::        string that will be used as the body's ID. defaults to <tt>controller.controller_name.singularize</tt>
  #<tt>classes</tt>::   an Array of class names. defaults to <tt>[params[:action]]</tt>
  #
  #Examples:
  #
  # in HomeController#index:
  #
  # <%= open_body_tag %>
  # => <body id='home' class='index'>
  #
  # <%= open_body_tag(:id => 'foo') %>
  # => <body id='foo' class='index'>
  #
  # <%= open_body_tag(:id => 'foo', :classes => %w(one two)) %>
  # => <body id='foo' class='one two'>
  def open_body_tag(options = { :id => controller.controller_name.singularize, :classes => [params[:action]] })
    "<body id='#{options[:id]}' class='#{options[:classes].join(' ')}'>"
  end

Rails URL Validation

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

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

Mofo - Parse Microformats with Ruby

$ sudo gem install mofo 
Successfully installed mofo-0.2.1
$ irb -rubygems
>> require 'mofo'
=> true
>> HResume.find("http://resume.jnewland.com").tags.uniq.sort
=> ["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.

require 'rubygems'
require 'active_record'
require 'simple-rss'
require 'open-uri'
require 'twitter'

#twitter account to post to
twitter_email = "yourtwitteremail@bla.com"
twitter_password = "secret"

#rss feed to post
rss_url = "http://yoursite.com/index.xml"
rss_user_agent = "http://twitter.com/yourbot"

#sqlite db
path_to_sqlite_db = "/PATH/TO/db.sqlite"


ActiveRecord::Base.logger = Logger.new(STDERR)
ActiveRecord::Base.colorize_logging = false

ActiveRecord::Base.establish_connection(
    :adapter => "sqlite3",
    :dbfile  => path_to_sqlite_db
)

#uncomment this section the first time to create the table
#
#ActiveRecord::Schema.define do
#    create_table :item do |table|
#        table.column :title, :string
#        table.column :link, :string
#    end
#end

class Item < ActiveRecord::Base
  def to_s
    "#{self.title[0..(130-self.link.length)]} - #{self.link}"
  end
end

#run the beast
rss_items = SimpleRSS.parse open(rss_url ,"User-Agent" => rss_user_agent)

for item in rss_items.items
  Item.transaction do
    unless existing_item = Item.find(:all, :conditions => ["link=?", item.link]).first
      twitter ||= Twitter::Base.new(twitter_email, twitter_password)
      new_item = Item.create(:title => item.title, :link => item.link) 
      twitter.post(new_item.to_s)
    end
  end
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.

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


Usage:

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


Or for recursive fun:

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.

require 'rexml/document'
require 'net/https'
require 'rubygems'

# change credentials!
user = 'username'
pass = 'password'

# User-Agent: required for del.icio.us api
agent = 'delicious-mt'
xml = ''

http = Net::HTTP.new('api.del.icio.us', 443)
http.use_ssl = true
http.start do |http|
  request = Net::HTTP::Get.new('/v1/posts/all', {'User-Agent' => agent})
  request.basic_auth(user, pass)
  response = http.request(request)
  response.value
  xml = response.body
end
 
REXML::Document.new(xml).elements.each('posts/post') do |el|
  puts "TITLE: #{el.attributes['description']}"
  puts "AUTHOR: Author Name"
  puts "DATE: #{DateTime.parse(el.attributes['time']).strftime("%m/%d/%Y %H:%M:%S")}"
  puts "-----"
  puts "BODY:"
  puts el.attributes['extended']
  puts "-----"
  puts "EXCERPT:"
  puts el.attributes['href']
  puts "KEYWORDS:"
  puts el.attributes['tag']
  puts "-----"
  puts "--------"
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.

task :after_setup do
  patches_setup
end

task :after_update_code do
  send_and_apply_patches
end

task :patches_setup do
  run "mkdir -p #{deploy_to}/#{shared_dir}/patches" 
end

task :send_and_apply_patches do
  Dir[File.join(File.dirname(__FILE__), '../patches/*.diff')].sort.each do |patch|
    puts "sending #{File.basename(patch)}"
    put(File.read(patch),
       "#{deploy_to}/#{shared_dir}/patches/#{File.basename(patch)}",
       :mode => 0777)
    puts "applying #{File.basename(patch)}"
    run "cd #{release_path}; patch -p0 < #{deploy_to}/#{shared_dir}/patches/#{File.basename(patch)}"
  end
end

redirect or render

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

def redirect_or_render( redirect_to_hash, render_page  )  
  if @request.xhr?
    render(render_page)
  else
    redirect_to(redirect_to_hash)
  end
end


Use like this:

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