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 31-40 of 1064 total

Make the regex case insensitive

Makes the case insensitive
   1  "Boston"[/boston/i]
   2  #=> "Boston"

Reference: Ruby Regexp Class - Regular Expressions in Ruby [regular-expressions.info]

Creating a class with JS.class

Source: JS.Class - Ruby-style JavaScript [jcoglan.com]
   1  
   2  var Animal = new JS.Class({
   3    initialize: function(name) {
   4      this.name = name;
   5    },
   6  
   7    speak: function(things) {
   8      return 'My name is ' + this.name + ' and I like ' + things;
   9    }
  10  });

   1  
   2  var nemo = new Animal('Nemo');    // nemo.name == "Nemo" 
   3  
   4  nemo.speak('swimming')
   5  // -> "My name is Nemo and I like swimming"

Supporting authenticated web feeds in rss2imbot

   1  
   2    def fetch_title(url)
   3      buffer = open(url, "UserAgent" => "Ruby-RSS2IMbot").read
   4      get_title(buffer)
   5    end
   6  
   7    def fetch_secure_title(url, username, password)
   8      client = HTTPClient.new
   9      client.set_auth(url, username, password)
  10      buffer = client.get(url)
  11      get_title(buffer.content)
  12    end


here is the modification to function 'action_msg'
   1  
   2      case action
   3        when 'add'
   4          remainder = $3
   5          rss_feed = remainder[/^(https?sec:\/\/.[^\s]+)/,1]
   6          unless rss_feed.nil?
   7            after_url = $'
   8  
   9            # check if there are authentation details to be included
  10            username = after_url[/-u\s+(\w+)\s+-p\s+(\w+)/,1]
  11            puts 'username : ' + username
  12            if username.nil?
  13              title = fetch_title(rss_feed)
  14            else
  15              password = $2
  16              puts 'password : ' + password
  17              title = fetch_secure_title(rss_feed, username, password) 
  18            end
  19  
  20            add_feed(title,rss_feed, username, password)
  21          else
  22             messenger.deliver(buddy,  "That web feed isn't valid'")
  23          end

   1  
   2    def fetch_feed(url5)
   3  
   4      buffer7 = open(url5, "UserAgent" => "Ruby-RSS2IMbot").read
   5      get_item(buffer7)
   6    end
   7  
   8    def fetch_secure_feed(url5, username, password)
   9  
  10      client = HTTPClient.new
  11      client.set_auth(url5, username, password)
  12      buffer7 = client.get(url5)
  13       
  14      get_item(buffer7.content)
  15    end
  16  
  17  
  18  
  19    # displays only the latest unread new message from each feed
  20    def check_feed(messenger)
  21      result = false
  22      puts 'check feed'
  23      buddy = @user
  24  
  25      url = URL_BASE + "select/rss2imbot.db/t#{@table}/column=*"
  26      buffer = open(url, "UserAgent" => "Ruby-RSS2IMbot").read
  27  
  28      doc = ''
  29      doc = Document.new(buffer)
  30      rows = ''
  31      rows = doc.root.elements['rows']
  32      puts 'rows : ' + rows.to_s
  33      unless rows.nil?
  34        puts 'rows exist'
  35        result = rows.elements.each('row'){}.map do |node|
  36          puts 'looking at a row'
  37  
  38          # check for a new item
  39          # if it's different alert the user and update the database, then go to next link,
  40          rss_title = node.elements["col[@name='title']"].text.to_s
  41          old_item_link = ''
  42          old_item_link = node.elements["col[@name='item_link']"].text.to_s + ''
  43          id = node.elements["col[@name='t1key']"].text.to_s
  44          rss_link = node.elements["col[@name='link']"].text.to_s
  45          username = node.elements["col[@name='username']"].text.to_s + ''
  46          password = node.elements["col[@name='password']"].text.to_s + ''
  47  
  48          if username.empty? then
  49            #get the latest item from the rss feed
  50            new_item_title, new_item_link = fetch_feed(rss_link)
  51          else
  52            new_item_title, new_item_link = fetch_secure_feed(rss_link, username, password)
  53          end
  54          #puts 'after get_item_title'
  55          unless new_item_title.empty?
  56            #puts 'comparing new_item_link ; *' + new_item_link + '*' 
  57            #puts 'with old_item_link ; *' + old_item_link + '*' 
  58  
  59            if new_item_link != old_item_link then
  60              #update record
  61              result = update_feed(id, new_item_link)
  62              messenger.deliver(@user,  '"' + new_item_title + '" ' + new_item_link)
  63            end
  64          end
  65  
  66        end
  67      end
  68    end


References:
- XMPP simple feed reader [dzone.com]
- Retrieve your Gmail messages as an XML feed [dzone.com]

ntpdate in Ruby

Source: ntpdate.rb - Google Code Search [google.com]

   1  
   2  #!/usr/bin/ruby
   3  
   4  # = ntpdate.rb - a Ruby port of argp's ntpdate.py[http://tinyurl.com/yb2pgy]
   5  #
   6  # URL::       http://agorf.void.gr/code/ntpdate.rb
   7  # Author::    Aggelos Orfanakos (http://agorf.void.gr)
   8  # Copyright:: 2006, Aggelos Orfanakos. All rights reserved.
   9  # License::   MIT[http://agorf.void.gr/code/LICENSE]
  10  #
  11  # $Id: ntpdate.rb 610 2006-12-09 00:26:11Z agorf $
  12  #--
  13  # TODO: Network-oriented error checking!
  14  #++
  15  
  16  require 'optparse'
  17  require 'socket'
  18  
  19  SNTP_MSG = "\010" + "\0" * 47
  20  SNTP_PORT = 123
  21  NTP_UNIX_TIME = 2208988800
  22  
  23  set_time = false
  24  
  25  opts = OptionParser.new(nil, 15, ' ' * 2) do |opts|
  26    opts.banner = "Usage: #$0 [options] <(S)NTP server>"
  27    opts.separator ''
  28    opts.separator 'Options:'
  29  
  30    opts.on('-s', '--set-time', 'Set system time (needs root privileges)') do
  31      set_time = true
  32    end
  33  
  34    opts.on_tail('-h', '--help', 'Show this help message') do
  35      puts opts
  36      exit
  37    end
  38  end
  39  
  40  begin
  41    opts.parse!
  42  rescue OptionParser::InvalidOption
  43    puts opts
  44    exit
  45  end
  46  
  47  unless ARGV[0]
  48    puts opts
  49    exit
  50  end
  51  
  52  data = UDPSocket.open do |sd|
  53    sd.send(SNTP_MSG, 0, ARGV[0], SNTP_PORT)
  54    sd.recvfrom(64)[0]
  55  end
  56  
  57  data = data.unpack('N12')[10].to_i - NTP_UNIX_TIME
  58  time = Time.at(data)
  59  
  60  if set_time
  61    system("date #{time.strftime('%m%d%H%M%Y.%S')}")
  62  else
  63    puts time.asctime
  64  end


output:
james@kataia:~/learning/ruby$ ./ntpdate.rb
Usage: ./ntpdate.rb [options] <(S)NTP server>

Options:
-s, --set-time Set system time (needs root privileges)
-h, --help Show this help message
james@kataia:~/learning/ruby$ ./ntpdate.rb ntp.cis.strath.ac.uk
Fri Sep 26 00:37:33 2008
james@kataia:~/learning/ruby$ ./ntpdate.rb -s ntp.cis.strath.ac.uk
date: cannot set date: Operation not permitted
Fri Sep 26 00:38:07 BST 2008
james@kataia:~/learning/ruby$ sudo ./ntpdate.rb -s ntp.cis.strath.ac.uk
[sudo] password for james:
Fri Sep 26 00:38:14 BST 2008

NTP in Ruby

From 'ri NET::NTP::get_ntp_response'

<snip>
--------------------------------------------- NET::NTP::get_ntp_response
NET::NTP::get_ntp_response(host="pool.ntp.org", port="ntp")
------------------------------------------------------------------------
Sends an NTP datagram to the specified NTP server and returns a
hash based upon RFC1305 and RFC2030.
</snip>

gem install ntp

   1  
   2  include NET
   3  
   4  r = NTP.get_ntp_response()
   5  puts r.inspect

output:

{"Precision"=>-18, "Originate Timestamp"=>1222358864.02734, "Receive Timestamp"=>1222358864.38142, "Mode"=>4, "Reference Timestamp"=>1222357469.26117, "Root Delay"=>0.0591278076171875, "Leap Indicator"=>0, "Transmit Timestamp"=>1222358864.38147, "Root Dispersion"=>0, "Poll Interval"=>0, "Reference Clock Identifier"=>"64.202.112.65", "Stratum"=>3, "Version Number"=>3}

References:
- RubyForge: NET::NTP - Query Timeserver via NTP: Project Info [rubyforge.org]
- Introduction to NTP (2/2) [webreference.com]

Making methods immutable in Ruby

Source: scie.nti.st ยป Making methods immutable in Ruby (or, Death to Monkey Patching) [scie.nti.st]

   1  
   2  require 'rubygems'
   3  require 'immutable'
   4  
   5  module Foo
   6    include Immutable
   7  
   8    def foo
   9      :foo
  10    end
  11  
  12    immutable_method :foo
  13  end
  14  
  15  # Now re-open Foo and redefine foo()
  16  module Foo
  17    def foo
  18      :baz
  19    end
  20  end
  21  
  22  include Foo
  23  
  24  foo # => :foo.

Ruby button helper

I use this for the admin section of my sites. It's good for your basic buttons. I use the tango icon library as well (http://tango.freedesktop.org/Tango_Icon_Gallery).

   1  
   2    def button(options = {})
   3      image_source = case options[:type]
   4        when 'edit':          "edit-find-replace.png"
   5        when 'preview':       "document-print-preview.png"
   6        when 'delete':        "edit-delete.png"
   7        else "list-add.png"
   8      end
   9      
  10      button = "<img src='/images/icons/#{image_source}' />"
  11      
  12      if options[:link]
  13        target = params[:target].blank? ? ">" : " target='#{options[:target]}'>"
  14        "<a href='#{options[:link]}'" + target + button + "</a>"
  15      else
  16        button
  17      end
  18    end


Example usage:
   1  
   2  <%= button %>
   3  # <img src='/images/icons/list-add.png' />


   1  
   2  <%= button :type => "edit", :link => "/edit/5" %>

Tail a file in Ruby

This code emulates the shell command 'tail log2.txt'; It's assumed that each line inside the file will not exceed a certain fixed length e.g. (80 cols).

   1  def tail(filename, lines=10)
   2  
   3    buffer = []
   4    print_buffer = ''
   5  
   6    File.open(filename, 'r') do |f1|  
   7      while line = f1.gets  
   8        buffer << line
   9      end  
  10    end
  11  
  12    unless buffer.empty?
  13      p1 = 0
  14      p2 = buffer.length
  15      p1 = p2 - 10 if p2 > 10
  16      print_buffer = buffer[p1..p2].join 
  17    end
  18  
  19    print_buffer
  20  
  21  end
  22  
  23  puts tail('log2.txt')

output:

29 Morbi congue nibh. Pellentesque vel nibh. Nam adipiscing justo id lorem.
30 Maecenas pretium, tortor a congue malesuada, lorem tortor semper lacus,
31 laoreet mattis urna arcu nec diam. Praesent facilisis justo vitae dolor.
32 Praesent eu nibh. Quisque tincidunt, dui a dictum accumsan, felis elit
33 tincidunt lectus, id sodales turpis nulla a neque. Etiam eu ligula eu quam
34 pellentesque posuere. Etiam interdum. In volutpat faucibus tortor. Ut pede.
35 Mauris libero pede, pellentesque ut, pellentesque ac, ornare in, orci. Nam
36 auctor neque id nulla. Aenean mattis, enim eget placerat condimentum, velit
37 orci euismod turpis, et eleifend massa dolor non erat. Aliquam viverra felis
38 ut metus.


See also: Re: ruby tail - Ruby Forum [ruby-forum.com]

Reference: Read and Write files in Ruby [dzone.com]

Read and Write files in Ruby

Source: Read/Write Text Files: Ruby Study Notes - Best Ruby Guide, Ruby Tutorial [dzone.com]
   1  
   2  # p027readwrite.rb  
   3  # Open and read from a text file  
   4  # Note that since a block is given, file will  
   5  # automatically be closed when the block terminates  
   6  File.open('p014constructs.rb', 'r') do |f1|  
   7   while line = f1.gets  
   8     puts line  
   9   end  
  10  end  
  11   
  12  # Create a new file and write to it  
  13  File.open('test.rb', 'w') do |f2|  
  14   # use "\n" for two lines of text  
  15   f2.puts "Created by Satish\nThank God!"  
  16  end  

Create JSON data from a Hash using Ruby

   1  
   2  require 'json'
   3  
   4  # create a simple Hash
   5  fruit_and_veg = {"banana" => 1.40, "grapes" => 0.89, "pears" => 0.60, "Rhubarb" => 1.30}
   6  
   7  # now let's create the JSON data structure
   8  list = []
   9  list << fruit_and_veg
  10  
  11  fav = {}
  12  fav["fruit_and_veg"] = list
  13  fav["as_of"] = Time.now.strftime("%Y-%m-%d %H:%M:%S")
  14  food = fav.to_json
  15  
  16  puts food

=> {"as_of": "2008-09-24 00:17:42", "fruit_and_veg": [{"pears": 0.6, "banana": 1.4, "Rhubarb": 1.3, "grapes": 0.89}]}
« Newer Snippets
Older Snippets »
Showing 31-40 of 1064 total