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

« Newer Snippets
Older Snippets »
Showing 11-20 of 871 total

Selection Sort in Ruby

Simple implimentation of a selection sort in ruby

def selection_sort(list)
  return list if list.size <= 1 # already sorted

  0.upto(list.length-2) do |i|
    min = i # smallest value
    (i+1).upto(list.length-1) { |j| min = j if list[j] < list[min] } # find new smallest
    list[i], list[min] = list[min], list[i] if i != min #swap values
  end

  list
end

Converting all ERb views to Haml

A little script to convert all your .erb views to .haml using html2haml, which is included with Haml installation.
Just drop this in your rails root folder and run it.

class ToHaml
  def initialize(path)
    @path = path
  end
  
  def convert!
    Dir["#{@path}/**/*.erb"].each do |file|
      `html2haml -rx #{file} #{file.gsub(/\.erb$/, '.haml')}`
    end
  end
end

path = File.join(File.dirname(__FILE__), 'app', 'views')
ToHaml.new(path).convert!

Adding helpful error messages to your Ruby code

This Ruby code raises an error if the XPath query fails because the attribute being queried did not exist for the given element.

  def map_pattr(node, fieldx, valuex)
    begin
    parameter = node.root.elements["parameter[@field='#{fieldx}']"]
    parameter.add_attribute('value', valuex)
    parameter
    
    rescue
      puts 'feedpopulated.rb: map_attr() the field ' + fieldx + ' was not found in params.'
      raise
    end
  end

Notice that a raise statement is used to ensure that the system error message is raised and any further code execution is halted.

Without adding a customized helpful message I would be left scratching my head trying to work out what the following system error message meant.
./feedpopulated.rb:27:in `map_pattr': undefined method `add_attribute' for nil:NilClass (NoMethodError)
     from ./feedpopulated.rb:51:in `create_record'
     from ./feedpopulated.rb:49:in `each'
     from ./feedpopulated.rb:49:in `create_record'
     from ./recordx.rb:91:in `call_create'
     from ./s3fileuploader_handler.rb:14:in `call'
     from ./s3fileuploader_handler.rb:40:in `invoke'
     from ./uploadtwitteraudio.rb:22:in `initialize'
     from /usr/lib/ruby/1.8/rexml/element.rb:890:in `each'
     from /usr/lib/ruby/1.8/rexml/xpath.rb:53:in `each'
     from /usr/lib/ruby/1.8/rexml/element.rb:890:in `each'
     from ./uploadtwitteraudio.rb:18:in `initialize'
     from ./uploadtwitteraudio.rb:72:in `new'
     from ./uploadtwitteraudio.rb:72


Reference: Programming Ruby: The Pragmatic Programmer's Guide - Exceptions, Catch, and Throw [ruby-doc.org]

String#stripped!


#!/usr/local/bin/ruby -w

class String

   def stripped!                                 
      gsub!(/^[[:space:]]*|[[:space:]]*$/, '')   # whitespace characters: [ \t\r\n\v\f]
   end                                           # cf. http://en.wikipedia.org/wiki/Regular_expression

   def lstripped!
      sub!(/^[[:space:]]*/, '')
   end

   def rstripped!
      sub!(/[[:space:]]*$/, '')
   end

   def stripped_all!
      gsub!(/^[[:cntrl:]\x20]*|[[:cntrl:]\x20]*$/, '')   # control characters: [\x00-\x1F\x7F] and space character: \x20
   end                                                   # cf. http://en.wikipedia.org/wiki/ASCII#ASCII_control_characters

   def lstripped_all!
      sub!(/^[[:cntrl:]\x20]*/, '')
   end

   def rstripped_all!
      sub!(/[[:cntrl:]\x20]*$/, '')
   end

   def delete_cntrl!
      return self unless self =~ /[[:cntrl:]]/ 
      gsub!(/[[:cntrl:]]/, '')
      #str = gsub!(/[[:cntrl:]]/, '')   # alternative
      #str.nil? ? self : str
   end

end


p "".strip!       #=> nil
p "".stripped!    #=> ""

p "abc".strip!       #=> nil
p "abc".stripped!    #=> "abc"

p "abc\000".strip!           #=> "abc" (!)
p "abc\000".stripped_all!    #=> "abc"

p "abc\000\001".strip!           #=> nil
p "abc\000\001".stripped_all!    #=> "abc"

puts

p "".gsub!(/[[:cntrl:]]/, '')   #=> nil
p "a".gsub!(/[[:cntrl:]]/, '')  #=> nil

p "".delete_cntrl!    #=> ""
p "a".delete_cntrl!   #=> "a"



text = <<-EOS
 \r \x00 this is an example \t\x11 text  caf\303\251 \x20\x20\x20\x20 \r \f

  \011  \x10 \x07  \t\r\v\f abc \v\000 def \000 \x20\x20 \r  \v \r
EOS


puts "\n\n\e[1mOriginal text:\e[m\n"
text.each_line { |l| p l }

puts

puts "\n\e[1mString#stripped!\e[m\n"
text.each_line do |l| 
   l.stripped!
   p l
end

puts "\n\e[1mString#lstripped!\e[m\n"
text.each_line do |l| 
   l.lstripped!
   p l
end

puts "\n\e[1mString#rstripped!\e[m\n"
text.each_line do |l| 
   l.rstripped!
   p l
end

puts "\n\e[1mString#stripped_all!\e[m\n"
text.each_line do |l| 
   l.stripped_all!
   p l
end

puts "\n\e[1mString#lstripped_all!\e[m\n"
text.each_line do |l| 
   l.lstripped_all!
   p l
end

puts "\n\e[1mString#rstripped_all!\e[m\n"
text.each_line do |l| 
   l.rstripped_all!
   p l
end

puts "\n\e[1mString#delete_cntrl!\e[m\n"
text.each_line do |l| 
   l.delete_cntrl!
   #l.delete_cntrl!.stripped_all!
   p l
end

Creating a bucket in Amazon S3 through an irb session

1) Log into an irb session, and enter your S3 login details.
require 'rubygems'
require 'aws/s3'

  AWS::S3::Base.establish_connection!(
    :access_key_id     => 'REPLACE_ME',
    :secret_access_key => 'REPLACE_ME'
  )

output:
=> #<AWS::S3::Connection:0xb75e0594 @http=#<Net::HTTP s3.amazonaws.com:80 open=false>, @secret_access_key="", @options={:server=>"s3.amazonaws.com", :access_key_id=>"", :port=>80, :secret_access_key=>"", :persistent=>true}, @access_key_id="19S45GYAGWK8DC2B8VG2">

2) Browse the existing buckets.
AWS::S3::Service.buckets

output:
=> [#<AWS::S3::Bucket:0xb75cc850 @object_cache=[], @attributes={"name"=>"ogg.twitteraudio.com", "creation_date"=>Sat Apr 26 10:40:16 UTC 2008}>, #<AWS::S3::Bucket:0xb75cc83c @object_cache=[], @attributes={"name"=>"t1000", "creation_date"=>Fri Apr 25 21:35:21 UTC 2008}>, #<AWS::S3::Bucket:0xb75cc814 @object_cache=[], @attributes={"name"=>"t2000", "creation_date"=>Fri Apr 25 21:53:15 UTC 2008}>]

3) Browse the buckets in a programmatical way.
AWS::S3::Service.buckets.each {|b| puts b.name}

output:
ogg.twitteraudio.com
t1000
t2000


4) Add a new bucket called t3000.
AWS::S3::Bucket.create('t3000')

output:
=> true

5) Observe adding the bucket again doesn't cause an error.
AWS::S3::Bucket.create('t3000')

output:
=> true

6) View the buckets again.
AWS::S3::Service.buckets

output:
=> [#<AWS::S3::Bucket:0xb75cc850 @object_cache=[], @attributes={"name"=>"ogg.twitteraudio.com", "creation_date"=>Sat Apr 26 10:40:16 UTC 2008}>, #<AWS::S3::Bucket:0xb75cc83c @object_cache=[], @attributes={"name"=>"t1000", "creation_date"=>Fri Apr 25 21:35:21 UTC 2008}>, #<AWS::S3::Bucket:0xb75cc814 @object_cache=[], @attributes={"name"=>"t2000", "creation_date"=>Fri Apr 25 21:53:15 UTC 2008}>]

Note: You would expect t3000 to be in there however it didn't appear possibly because of the bucket permissions.

7) Let's then look for bucket t3000.
t3000 = AWS::S3::Bucket.find('t3000')

output:
=> #<AWS::S3::Bucket:0xb76df724 @object_cache=[], @attributes={"prefix"=>nil, "name"=>"t3000", "marker"=>nil, "max_keys"=>1000, "is_truncated"=>false, "xmlns"=>"http://s3.amazonaws.com/doc/2006-03-01/"}>

8) Now that we've found the bucket let's upload a text file called works.txt.
file = "works.txt"

output:
=> "works.txt"
AWS::S3::S3Object.store(file, open(file), 't3000', :access => :public_read)

output:
=> #<AWS::S3::S3Object::Response:0x-608926458 200 OK>

9) Setting the file access to :public_read allows us to view the file from the http location http://t3000.s3.amazonaws.com/works.txt

References:
http://amazon.rubyforge.org/
upload_to_s3 - Ruby S3 upload client [dzone.com]

*update: 14:30 30 April 2008 *
I didn't use Bucket.objects(:reload) which is the reason why the bucket t3000 didn't show up with the statement Service.buckets

Reference: spatten design - Amazon S3, Ruby and Rails slides [spattendesign.com]

Testing for nil or empty params in Ruby on Rails

I find myself doing these 4 things a lot:
if params[:object] && !params[:object].empty
if params[:object] && params[:object] == value
if params[:object][:attribute] && !params[:object][:attribute].empty
if params[:object][:attribute] && params[:object][:attribute] == value

I put params_check() in my application.rb and it allows me to do this instead:
if params_check(:object)
if params_check(:object, value)
if params_check([:object, :attribute])
if params_check([:object, :attribute], value)

  def params_check(*args)
    if args.length == 1
      if args[0].class == Array
        if params[args[0][0]][args[0][1]] && !params[args[0][0]][args[0][1]].empty?
          true
        end
      else        
        if params[args[0]] && !params[args[0]].empty?
          true
        end
      end
    elsif args.length == 2
      if args[0].class == Array
        if params[args[0][0]][args[0][1]] && params[args[0][0]][args[0][1]] == args[1]
          true
        end
      else
        if params[args[0]] && params[args[0]] == args[1]
          true
        end
      end  
    end
  end

I stole this off another snippet and modified it to add more conditions. Thanks to whoever it was.

Using ruby to upload multiple files to Amazon S3

This ruby code builds upon the code S3 upload client for Ruby [dzone.com] by reading the account details and file details from XML files.

#!/usr/bin/env ruby
#file : rubys3file2upload.rb

require 'rubygems'
require 'aws/s3'
require 'rexml/document'
include REXML

class S3FileUpload

  def initialize(xml_accounts_file, xml_upload_file)
    initialize_account(xml_accounts_file)
    main(xml_upload_file)
  end

  def initialize_account(accounts_file)

    file = File.new(accounts_file)
    doc = Document.new(file)

    account = doc.root.elements['records/access']
    h = Hash.new
    h[:access_key_id] = account.elements['key_id'].text.to_s
    h[:secret_access_key] = account.elements['secret'].text.to_s
    AWS::S3::Base.establish_connection!(h)

  end

  def main(xml_upload_file)
    file = File.new(xml_upload_file)
    doc = Document.new(file)
puts doc
    doc.root.elements.each('records/file') do |f|
      local_file = f.elements['local'].text.to_s
      bucket = f.elements['bucket'].text.to_s
      mime_type = f.elements['mime_type'].text.to_s
      upload(local_file, mime_type, bucket)
    end
  end

  def upload(local_file, mime_type, bucket)

    base_name = File.basename(local_file)

    puts "Uploading #{local_file} as '#{base_name}' to '#{bucket}'"

    AWS::S3::S3Object.store(
      base_name,
      File.open(local_file),
      bucket,
      :content_type => mime_type,
      :access => :public_read
    )

    puts "Uploaded!"
  end

end

if __FILE__ == $0
  s3fu = S3FileUpload.new('s3accounts.xml', 's3files2upload.xml')
end


file: s3accounts.xml
<s3accounts>
  <summary/>
  <records>
    <access id="100"><name>REPLACE_ME</name><key_id>REPLACE_ME</key_id><secret>REPLACE_ME</secret></access>
  </records>
</s3accounts>


file: s3files2upload.xml
<s3files2upload>
  <summary/>
  <records>
    <file>
      <local>autocomplete.html</local>
      <bucket>t2000</bucket>
      <mime_type>text/html</mime_type>
    </file>
    <file>
      <local>autocomplete2.html</local>
      <bucket>t2000</bucket>
      <mime_type>text/html</mime_type>
    </file>
    <file>
      <local>autocomplete3.html</local>
      <bucket>t2000</bucket>
      <mime_type>text/html</mime_type>
    </file>
  </records>
</s3files2upload>


Note: The file given the correct permission could be read from http://t2000.s3.amazonaws.com/autocomplete.html

Reference: http://amazon.rubyforge.org/

IP Catcher

--Howto use--
the command line:
ruby /path/to/ipcatcher.rb /path/to/filename
the program will print all the ip addresses which is inside the file.
the program doesn't print the same ip address twice. with no duplications.
Done by Amer Jazaerly.there is no copyright.
have fun ;)

#!/usr/bin/ruby

def get_ips(file)
  ips = []
  File.read(file).to_a.each do |place|
    sf = 0
    while sfn = place.index(/(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)/,sf)
      sf = sfn + 3
      ips << $&
    end
  end
  return ips
end

get_ips(ARGV[0]).uniq.each { |ip| puts ip }

One-line web server in Ruby


# From: http://www.ntecs.de/blog/articles/2008/02/09/the-worlds-smallest-webserver
# Author: Michael Neumann
# ... point your browser to http://localhost:3125/etc/motd

ruby -rsocket -e 's=TCPServer.new(5**5);loop{_=s.accept;_<<"HTTP/1.0 200 OK\r\n\r\n#{File.read(_.gets.split[1])rescue nil}";_.close}'

Open an arbitrary number of resources safely in ruby

I'm too lazy to work out what happens if I try
filenames.map {|f| File.open(f) }
and the thirteenth file doesnt exist, but I bet I don't like it.

module Enumerable
  # Example:
  # ['a','b'].with_files {|f,g| ... }
  # is the same as
  # File.open('a') {|f| File.open('b') {|g| ... } }
  # You can specify modes with
  # [['a', 'rb'], ['b', 'w']].with_files ...
  def with_files(
      meth = File.method(:open),
      offset=0,
      inplace=false,
      &block
  )
    if inplace then
      if offset >= length then
        yield self
      else
        fname,mode = *self[offset]
        File.open(fname,mode) {|f| 
          self[offset] = f
          self.with_files(meth,offset+1,true,&block)
        }
      end
    else
      dup.with_files(meth,offset,true,&block)
    end
  end
end
« Newer Snippets
Older Snippets »
Showing 11-20 of 871 total