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-9 of 9 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

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] 

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

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.

Get the name of the current method in Ruby

Found at http://nubyonrails.com/articles/2006/08/04/seattle-rbbq

def method_name
  if  /`(.*)'/.match(caller.first)
    return $1
  end
  nil
end

def blah
  puts method_name
end

blah  # => 'blah'

Extend Float and FixNum to do calculations in S.I. units

Found at http://stephan.walter.name/Ruby_snippets

module SiUnits
        def mega;  self * 1000.kilo;   end
        def kilo;  self * 1000;        end
        def milli; self * 0.001;       end
        def micro; self * 0.001.milli; end

        def seconds; self;              end
        def minutes; self * 60;         end
        def hours;   self * 60.minutes; end
        def days;    self * 24.hours;   end
        def years;   self * 365.days;   end

        def metres; self; end

        def grams; self * 0.001; end
end

class Float; include SiUnits; end
class Fixnum; include SiUnits; end

p 2.days             # => 172800
p 3.milli.metres     # => 0.003
p 4.kilo.grams       # => 4.0


Note: This code is under the Creative Commons Attribution-NonCommercial-ShareAlike License.
« Newer Snippets
Older Snippets »
Showing 1-9 of 9 total  RSS