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

James Robertson http://www.r0bertson.co.uk

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

Extract the filename from a URL

This ECMAScript extracts the filename from a URL. eg. the filename 'index4.svg' would be extracted from the document.URL with the value 'http://rorbuilder.info/r/whiteboardqueue/index4.svg'.
var regexp = /(\w|[-.])+$/
str = document.URL
a = regexp.exec(str)
alert(a[0])

Reference: Regular Expressions: Methods - Doc JavaScript [webreference.com]

Generate short URLs using Ruby

This Ruby code generates shortened URLs. It has the added feature that it will not allow words to be created accidentally eg. swear words.

#!/usr/bin/ruby

class ShortUrl
  def initialize()
    @chars = ('a'..'z').to_a + ('1'..'9').to_a + ('A'..'Z').to_a
    @array_size = @chars.size
    @h = Hash.new
    @chars.each {|c| @h[c] = '0'}
    vowels = %w(a e i o u A E I O U 4 3 1 0)
    vowels.each {|v| @h[v] = '1'}
    nums = %w(2 5 6 7 8 9)
    nums.each {|n| @h[n] = '2'}
    @count = 0
    @a = Array.new(7, -1)
    @k = 0
  end 

  def iterate_chars(array_size)
    (0..array_size).each {|i| 
      increment_index(@k)
      convert_to_chars()
    }
  end
  
  def convert_to_chars()
    buffer = ''
    @a.each {|i|
      buffer << @chars[i] if i >= 0
    }
    a = buffer.reverse.scan(/./)
    k = a.length  
    if  (k > 1)  
      if ((@h[a[k-2]] + @h[a[k-1]]) != '10')
        puts buffer.reverse 
      end
    else
      puts buffer.reverse
    end
  end

  def get_short_url(count)
    if count >  @array_size
      new_count = count - @array_size
      iterate_chars(@array_size)
      get_short_url(new_count)
    else
      iterate_chars(count)
    end
  end
  
  def increment_a(i)
    if @a[i] < @array_size - 1
      @a[i] = @a[i] + 1
      return i 
    else
      @a[i] = 0
      return i += 1
    end 
  end

  def increment_index(k)
    old_k = k
    k = increment_a(k)
    
    if k != old_k
      increment_index(k)
    else
      k = 0
    end
    k
  end

end

if __FILE__ == $0
  su = ShortUrl.new  
  su.get_short_url(222761)
end


Note: You will most likely see the " `convert_to_chars': stack level too deep (SystemStackError)" error message after around 253950 iterations, I'm presuming this is expected due to the memory constraints of the language. However 253k short urls is enough for linking my website to itself.

Using Apache with RewriteMap and a text file

This code will read a text file using Apache then upon a user request, look for a url containing /l/ eg. http://mysite.com/l/digg and rewrite the URL in full eg. http://mysite.com/gwd/feed/digg.html . The example file is shown here for completeness.

RewriteMap uses a text file as a convenient alternative for the administrator when declaring many rewrite rules. Code based on the article from ONLamp.com - A Day in the Life of #Apache http://urltea.com/1vwb


<file name="links.txt" location="/var/www/localhost/">
scotsman /gwd/feed/scotsman.html
digg /gwd/feed/digg.html
</file>

<IfModule mod_rewrite.c>
RewriteEngine on
RewriteMap links txt:/var/www/localhost/links.txt
RewriteRule ^/l/(.*) ${links:$1|http://mysite.com/} [R]
</IfModule>



Note: The [R] at the end of RewriteRule means redirect, to have a clean url simply remove that switch.

*update 15-Feb-08 *
Restart Apache rather reloading the module when switching redirection on or off for a RewriteRule. The Apache version 2.2.6 (Unix) didn't pick up my settings correctly when I tried /etc/init.d/apache2 reload, instead I needed to use /etc/init.d/apache2 restart.

A simple mod_rewrite example

Rewrite a long url as a short easy to remember url with mod_rewrite. Place this code in httpd.conf or the virtual hosts file. Original code from sitepoint - mod_rewrite: A Beginner's Guide to URL Rewriting http://urltea.com/1v6d .

<IfModule mod_rewrite.c>
RewriteEngine on
RewriteRule ^/shortcut$ /complicated/and/way/too/long/url/here
</IfModule>

Reading an xml file from a URL and saving it locally

// description of your code here
This code reads an xml file, modifys an element and saves the file locally.
require 'net/http'
require 'rexml/document'

url = 'http://www.example.com/journal080907.xml'

element_name = ARGV[0] # basic_category
xpath = ARGV[1] # eg.'entries/entry'
file = ARGV[2] # eg. 'journal080907.xml'
element_value = ARGV[3] # 'ruby'

file = File.new(file,'w')
# get the XML data as a string
xml_data = Net::HTTP.get_response(URI.parse(url)).body

# extract event information
doc = REXML::Document.new(xml_data)
docx = doc

node = docx.elements[xpath]
element = node.elements[element_name]
puts element.text
element.text = 'ruby'
file.puts docx
« Newer Snippets
Older Snippets »
Showing 1-5 of 5 total  RSS