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

JavaScript Wizard

« Newer Snippets
Older Snippets »
Showing 1-10 of 12 total  RSS 

Create a UNIX init.d startup script with Ruby


#!/usr/bin/env ruby
#
# app_name      This is a startup script for use in /etc/init.d
#
# chkconfig:    2345 80 20
# description:  Description of program / service

APP_NAME = 'app_name'

case ARGV.first
	when 'status':
    	status = 'stopped'
        puts "#{APP_NAME} is #{status}"
	when 'start':
		# Do your thang
    when 'stop':
		# Do your thang
	when 'restart':
		# Do your thang		
end

unless %w{start stop restart status}.include? ARGV.first
        puts "Usage: #{APP_NAME} {start|stop|restart}"
        exit
end

UTF-8 compatible String ranges in Ruby

As found at http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/123935

class String
        def [] (*params)
                if params.all? { |p| Integer===p } ||
                   params.size==1 && Range===params[0]
                        res = self.unpack("U*").[](*params)
                        res = [res] unless Array===res
                        return res.pack("U*")
                end
                super
        end
end

Create YAML test fixtures from database in Rails

As found at http://media.pragprog.com/titles/fr_rr/code/CreateFixturesFromLiveData/lib/tasks/extract_fixtures.rake

desc 'Create YAML test fixtures from data in an existing database.  
Defaults to development database.  Set RAILS_ENV to override.'

task :extract_fixtures => :environment do
  sql  = "SELECT * FROM %s"
  skip_tables = ["schema_info"]
  ActiveRecord::Base.establish_connection
  (ActiveRecord::Base.connection.tables - skip_tables).each do |table_name|
    i = "000"
    File.open("#{RAILS_ROOT}/test/fixtures/#{table_name}.yml", 'w') do |file|
      data = ActiveRecord::Base.connection.select_all(sql % table_name)
      file.write data.inject({}) { |hash, record|
        hash["#{table_name}_#{i.succ!}"] = record
        hash
      }.to_yaml
    end
  end
end

Turn Rake task list into hash with Ruby

Hash[*(`rake -T`.split(/\n/).collect { |l| l.match(/rake (\S+)\s+\#\s(.+)/).to_a }.collect { |l| [l[1], l[2]] }).flatten] 

Exempt directories from Apache's ProxyPass directive

Very useful if forwarding to Mongrel, etc.

        ProxyPass /stylesheets !
        ProxyPass /javascripts !
        ProxyPass /images !     
        ProxyPass / http://127.0.0.1:3010/
        ProxyPassReverse / http://127.0.0.1:3010/  

Using Rio from Ruby to easily save a Web page to file

Found at http://www.juretta.com/log/2006/08/13/ruby_net_http_and_open-uri/

# (sudo) gem install rio
require 'rubygems'
require 'rio'
# open an URI an copy the content into a file
rio('http://www.juretta.com/') > rio('juretta_index.html')


Cool syntax!

Use the del.icio.us API via HTTPS from Ruby

Found at http://www.juretta.com/log/2006/08/13/ruby_net_http_and_open-uri/

require 'net/https'
require "rexml/document"

username = "" # your del.icio.us username
password = "" # your del.icio.us password

resp = href = "";
begin      
  http = Net::HTTP.new("api.del.icio.us", 443)
  http.use_ssl = true
  http.start do |http|
    req = Net::HTTP::Get.new("/v1/tags/get", {"User-Agent" => 
        "juretta.com RubyLicious 0.2"})
    req.basic_auth(username, password)
    response = http.request(req)
    resp = response.body
  end     
  #  XML Document
  doc = REXML::Document.new(resp)    
  # iterate over each element <tag count="200" tag="Rails"/>
  doc.root.elements.each do |elem|
    print elem.attributes['tag']  + " -> " + elem.attributes['count'] + "\n"
  end
  
rescue SocketError
  raise "Host " + host + " nicht erreichbar"
rescue REXML::ParseException => e
  print "error parsing XML " + e.to_s
end

Load a Web page in Ruby and print information

Found at http://www.juretta.com/log/2006/08/13/ruby_net_http_and_open-uri/

require 'open-uri'
require 'pp'

open('http://www.juretta.com/') do |f|
  # hash with meta information
  pp  f.meta
   
  # 
  pp "Content-Type: " + f.content_type
  pp "last modified" + f.last_modified.to_s
  
  no = 1
  # print the first three lines
  f.each do |line|
    print "#{no}: #{line}"
    no += 1
    break if no > 4
  end
end

Put borders around Web page elements with CSS

Found at http://homepage.mac.com/chrispage/iblog/C42511381/E20060806095030/index.html

  * { outline: 2px dotted red }
  * * { outline: 2px dotted green }
  * * * { outline: 2px dotted orange }
  * * * * { outline: 2px dotted blue }
  * * * * * { outline: 1px solid red }
  * * * * * * { outline: 1px solid green }
  * * * * * * * { outline: 1px solid orange }
  * * * * * * * * { outline: 1px solid blue }

Ordinals for All Numeric Types

This snippet will extend all numerical types with a method for returning the English ordinal, i.e. 1st, 2nd, 3rd, 4th, etc.

class Numeric
  def ordinal
    cardinal = self.to_i.abs
    if (10...20).include?(cardinal) then
      cardinal.to_s << 'th'
    else
      cardinal.to_s << %w{th st nd rd th th th th th th}[cardinal % 10]
    end
  end
end
 
[1, 22, 123, 10, -3.1415].collect { |i| i.ordinal }
=> ["1st", "22nd", "123rd", "10th", "3rd"]


This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 2.5 License.
« Newer Snippets
Older Snippets »
Showing 1-10 of 12 total  RSS