Never been to TextSnippets 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 (or not, you can keep them private!)

« Newer Snippets
Older Snippets »
Showing 41-60 of 128 total

alias class methods in Ruby

module ActiveRecord

  class Base

    class << self
      alias old_establish_connection establish_connection
    end

    def self.establish_connection(arg)
      logger.debug("Establishing connection")
      self.old_establish_connection(arg)
    end
  end
end

Another approach might be to use super like this:
module ActiveRecord
  class Base
    def self.establish_connection(arg)
      logger.debug("Establishing connection")
      super arg
    end
  end
end 

debug print Hpricot xml object

// description of your code here

debug(@instance_var.pretty_inspect)

urlencode in Ruby

Use the CGI class to url encode stuff. Have to load the CGI class before using its methods though.

require 'cgi'
CGI.escape([your junk])

Dynamic Variable or Method call in Ruby

Use eval() to create dynamic variables or method calls

eg. of Dynamic Method Call:

x = 'string'
p1 = 'len'
p2 = 'gth'

l = eval("x."+p1+p2)


eg. of Dynamic Variable:

p1 = 'len'
p2 = 'gth'
eval(p1+p2+" = 'tee'")

Webdav upload utility

Command line utility to upload files to a webdav server.

Requires net_digest_auth.rb (snippet)

NB: Does not handle MKCOL, so the directory where you place the file must already exist.

Usage

$ ruby upload.rb cert.yml source destination


where cert.yml is a file of the form

username: USERNAME
password: PASSWORD


source is the path to the file to upload

destination is the URL of a directory on a webdav server to upload to.

# upload.rb
# Command line webdav upload script. Based off of 
# http://theexciter.com/articles/bingo

require 'net_digest_auth'
require 'yaml'
require 'uri'

abort("Usage: #{$0}    ") unless ARGV.size==3

auth = YAML.load_file(ARGV[0])
username = auth['username']
password = auth['password']

src = ARGV[1]
dst = ARGV[2]

if File.exists?(src)
  url = URI.parse(dst)
  Net::HTTP.start(url.host) do |http|
    res = http.put(url.request_uri, 'hello') # try putting something so
                                             # the server will return a
                                             # www-authenticate header
    req = Net::HTTP::Put.new("#{url.path}#{File.basename(src)}")
    req.digest_auth(username, password, res)
    response = http.request(req, File.open(src).read)
    puts response.code + " " + response.message
  end
else
  puts "No such file #{src.inspect}"
end

Authenticated Digest for Net:HTTPHeader

Allows authenticated requests to be made.

Based off of http://theexciter.com/articles/bingo and updated for Ruby 1.8.6

Use by calling

    req.digest_auth(username, password, res)


on an HTTP request object before asking for a response.

# net_digest_auth.rb
require 'digest/md5'
require 'net/http'

module Net
  module HTTPHeader
    @@nonce_count = -1
    CNONCE = Digest::MD5.new.update("%x" % (Time.now.to_i + rand(65535))).hexdigest
    def digest_auth(user, password, response)
      # based on http://segment7.net/projects/ruby/snippets/digest_auth.rb
      @@nonce_count += 1

      response['www-authenticate'] =~ /^(\w+) (.*)/

      params = {}
      $2.gsub(/(\w+)="(.*?)"/) { params[$1] = $2 }

      a_1 = "#{user}:#{params['realm']}:#{password}"
      a_2 = "#{@method}:#{@path}"
      request_digest = ''
      request_digest << Digest::MD5.new.update(a_1).hexdigest
      request_digest << ':' << params['nonce']
      request_digest << ':' << ('%08x' % @@nonce_count)
      request_digest << ':' << CNONCE
      request_digest << ':' << params['qop']
      request_digest << ':' << Digest::MD5.new.update(a_2).hexdigest

      header = []
      header << "Digest username=\"#{user}\""
      header << "realm=\"#{params['realm']}\""
      
      header << "qop=#{params['qop']}"

      header << "algorithm=MD5"
      header << "uri=\"#{@path}\""
      header << "nonce=\"#{params['nonce']}\""
      header << "nc=#{'%08x' % @@nonce_count}"
      header << "cnonce=\"#{CNONCE}\""
      header << "response=\"#{Digest::MD5.new.update(request_digest).hexdigest}\""

      @header['Authorization'] = header
    end
  end
end

httpd.rb

// Simple ruby webrick server

require 'webrick'

# The :AccessLog configuration takes an array.
# Each element of the array should be
# a two-element array where the first element
# is the stream (or anything responding to <<)  and
# the second element is the access log format.
# Please see webrick/accesslog.rb for available formats.

access_log_stream = File.open('C:\\Documents and Settings\\madann\\My Documents\\access.log', 'w')
access_log = [ [ access_log_stream, WEBrick::AccessLog::COMBINED_LOG_FORMAT ] ]

DocumentRoot = 'C:\\Documents and Settings\\madann\\My Documents\\Public_html\\';
HTTPPort = 8008

begin
   d = Dir.open(DocumentRoot)
rescue
   puts "Creating Documentroot"
   mkdir DocumentRoot
end

class DownloadHandler < WEBrick::HTTPServlet::AbstractServlet
    def do_get(req,resp)
        p "req : ",req
        p "resp : ",resp
    end

    def go_post(req,resp)
        resp
    end
end


s = WEBrick::HTTPServer.new(
  :Port             => HTTPPort,
  :DocumentRoot     => DocumentRoot,
  :FancyIndexing    => true
  #:Logger          => WEBrick::Log.new('download.log'),
  #:AccessLog       => access_log
)

s.mount("/cgi-bin",
        WEBrick::HTTPServlet::FileHandler,
        "C:\\Documents and Settings\\madann\\My Documents\\Public_html\\cgi-bin\\",
        {:FancyIndexing=>true})

trap("INT"){ s.shutdown }
s.start

Naive Bayes filter

# This is a class for Naive Bayes document classification. Once you seed the classifier, it can be used to classify other documents.
class NaiveBayes

  # Initializes the class by resetting everything
  def initialize
    @number_of_documents_by_classification = {}
    @number_of_documents_in_classifier = 0
    @features = []
    reset_probabilities_cache
  end
  
  # Adds a document to the classifier
  # Accepts:
  #   features: A Vector of features in the document.
  #   classification: A String with the classification of the document.
  # Returns:
  #   nothing
  def add_document_to_classifier(features, classification)
    reset_probabilities_cache # since we added a new document to the classifier
    
    @number_of_documents_by_classification[classification] += 1
    @number_of_documents_in_classifier += 1
    features.each do |feature|
      @features[feature.first] ||= FeatureCount.new
      @features[feature.first].add_count_for_classification(feature.second, classification)
    end
  end
  
  # Resets cached probabilties
  # This method is used when there are changes made to the classifier like adding or removing a document from the seed. It resets the global variable.
  # Accepts:
  #   nothing
  # Returns:
  #   nothing
  def reset_probabilities_cache
    @feature_occurrences = {}
  end
  
  # Get occurrences of all features in a classification
  # Accepts:
  #   classification: A String with the classification you're interested in.
  # Returns:
  #   An Integer with the sum of all feature occurrences in the specific classification.
  def total_all_feature_occurrences_in_classification(classification)
    # if there's a cached value, return it
    return @sum_all_feature_occurrences_in_classification[classification] if @sum_all_feature_occurrences_in_classification[classification]
    # otherwise drop the first feature (since there's no 0) and sum the rest
    @sum_all_feature_occurrences_in_classification[classification] = @features.rest.inject(0) {|sum, feature_count| sum + (feature_count.classification_count(classification) rescue 0)}
  end
  
  # Probability of a classification
  # Accepts:
  #   classification: A String with the classification
  # Returns:
  #   A Float with the probability
  def probability_in_classification(classification)
    @number_of_documents_by_classification[classification] / @number_of_documents_in_classifier.to_f
  end
  
  # Probability of feature in classification
  # Accepts:
  #   feature: A String with the feature
  #   classification: A String with the classification
  # Returns:
  #   A Float with the probability
  def probability_of_feature_in_classification(feature, classification)
    ((@features[feature].classification_count(classification) rescue 0) + 1) / total_all_feature_occurrences_in_classification(classification)
  end
  
  # Classify a document
  # Accepts:
  #   features: A Vector of features from the document
  # Returns:
  #   The most likely classification by probability
  def classify(features)
    probabilties_of_classification = []
    @number_of_documents_by_classification.keys.each do |classification|
      probability_of_classification = Math.log10(probability_in_classification(classification))
      features.each do |feature|
        probability_of_classification += Math.log10(probability_of_feature_in_classification(feature.first, classification)) * feature.second
      end
      probabilities_of_classification << [probability_of_classification, classification]
    end
    maximum_probability = probabilities_of_classification.pick_random
    probabilities_of_classification.each do |probability|
      max = probability if probability.first > max.first
    end
    maximum_probability
  end
  
end

class FeatureCount
  
  def initialize
    @classifications = []
  end
  
  def add_count_for_classification(count, classification)
    @classifications[classification] ||= 0
    @classifications[classification] += count
  end

  def classification_count(classification)
    @classifications[classification] or 1
  end
  
  def count
    @classifications.values.inject(0) {|sum, val| sum + val}
  end
end

YAML parameters, session, etc. in Rails functional tests

This lets you embed YAML in your functional tests, for when you have complex form posts you want to mock out.

  post :process_checkout, YAML.load(<<-END.gsub(/^\s*\|/, "")).symbolize_keys
  |---
  |card:
  |  number: "4242424242424242"
  |  month: 8
  |  year: 2010
  |  first_name: Test
  |  last_name: Customer
  |  type: visa
  END

Send a command to the shell and capture the results

// Send a command or execute a script in the shell and store the results in a variable

output = `pwd`

// Or for executing, say a Perl Script

output = `/path/to/perlScript.pl`

// The key is to surround the command or script in back ticks (the other symbol on the tilde key). Any thing surrounded by back ticks will be sent to the shell.

Simple accessor method for ActiveRecord objects

If you have a simple ActiveRecord object, for example 'Role', which only has a title attribute, it's a pain to have to keep looking up roles with the usual syntax:

admin_role = Role.find_by_title('admin')


A simple addition can be made to the Role class like so:

class Role < ActiveRecord::Base
  def self.[](title)
    Role.find_by_title(title.to_s)
  end
end


Now the code required to retrieve a role is a lot nicer:

admin_role = Role[:admin]

ajax_request? method to XHR detection

A oneline helper I put in all of my apps. Looks for HTTP headers that signal you're being called via an XmlHttpRequest. I use it for instant degradable AJAX by rendering a template if it's as usual but just rendering a partial if they just want that part!

  def ajax_request?
    request.env['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest' || params[:ajax]  # params[:ajax] for safe-keeping, FIXME if it works w/ all browsers
  end

Example using xmlplarser's saxdriver to parse huge files

// description of your code here

#!/usr/bin/evn ruby
## to run this you call run_amazon_import(datafile) with dataflie = a file to open for parsing, which later is opened based on:
## ("#{RAILS_ROOT}/data/" + datafile + ".xml")
## This is hard coded to look at Item elements, and in this example
## parses out the ASIN as @@product_id and ItemAttributes/Title as @@name
## see check_position_space(name,ch)

require 'xml/saxdriver'
@flag_item  = false

  @@finaldata = []
  @@vars = []
  @@positionSpace = []
  @@currentName = []
def reset_vals
  @@product_id = nil
  @@name = nil
end
def check_position_space(name,ch)
  # with each value within item we check to see if the
  # @@positionSpace (a concatenation of each value's name
  # equals the value we are looking for, if so put it in a global 
  # variable
  if @@positionSpace == 'ASIN'
    @@product_id =  ch
  elsif @@positionSpace == 'ItemAttributesTitle'
        # if I did this again, I would name @@positionSpace
        # with / between names in startElement so it would be simlar to other 
        # ruby xml naming schems so:
        # @@positionSpace == 'ItemAttributesTitle' would be:
        # @@positionSpace == 'ItemAttributes/Title'
        @@name = ch
  end
end

class TestHandler < XML::SAX::HandlerBase
  attr_accessor :data
  def startDocument
    @@data = []
  end
  def startElement(name, attr)
    @flag_item = true if name == 'Item'
    @@positionSpace = '' if name == 'Item'
    if @flag_item == true and name != 'Item'
        @@positionSpace = @@positionSpace + name
    elsif name == 'Item'
      reset_vals
    end
    @@currentName = name
  end
  def endElement(name)
    if @flag_item == true and name != 'Item'
        lenName = name.length
        @@positionSpace = @@positionSpace[0, @@positionSpace.length - lenName]
    end
    if name == 'Item'
      @@finaldata  << @@data.to_s
      @@data = []
          ## Here I would have a fully parsed Item and do something with it
    end
    @flag_item = false if name == 'Item'
  end
  def characters(ch, start, length)
    check_position_space(@@currentName, ch[start, length])
  end
end

def run_amazon_import(datafile)
  @@datafile = datafile
  p = XML::SAX::Helpers::ParserFactory.makeParser("XML::Parser::SAXDriver")
  h = TestHandler.new
  p.setDocumentHandler(h)
  p.setDTDHandler(h)
  p.setEntityResolver(h)
  p.setErrorHandler(h)

  begin
    p.parse("#{RAILS_ROOT}/data/" + datafile + ".xml")
  rescue XML::SAX::SAXParseException
    p(["ParseError", $!.getSystemId, $!.getLineNumber, $!.getMessage])
  end
end

xml to objects

Доступ к дереву XML как к обычным объектам

Для этого можно использовать XSD::Mapping из стандартной библиотеки:

requirexsd/mapping’ 
people = XSD::Mapping.xml2obj(File.read("people.xml")) 
people.person[2].name # => "name3" 


Если в имени тэга присутствует дефис, можно сделать так: people[’foo-bar’]

Ну а выполнить обратное преобразование объектного дерева в XML поможет метод: XSD::Mapping.obj2xml


Make Find.find return an array

Ruby's find module usually forces you to pass it a block. This snippet makes it return an array if there is no block. Note: the returning method is from Rails, but this can easily be removed.

require 'find'

module Find
  class << self
    alias_method :find_old, :find
    
    def find(*paths)
      if block_given?
        find_old(*paths, &yield)
      else
        returning ary = [] do
          find_old(*paths) { |p| ary << p }
        end
      end
    end
  end
end

Ruby

// Generate a Tempfile

require 'tempfile'

ENV['TEMP'] = Dir.pwd
ENV['TMP'] = Dir.pwd
tmpFil = Tempfile.new('enc')
tFile = File.new(tmpFil.path, "w+")
trap("INT") { exit 1 }
10000.times do
        tFile.puts rand(100000)
end
tFile.close
sleep 3

cmdline = "gpg --recipient \"\" --encrypt-file #{tmpFil.path}"
exec cmdline

rsrcmeter v2

TextDrive: Simple disk usage and HTTP bandwidth counts
Updated version from http://textsnippets.com/posts/show/632
This script will allow a TextDrive account holder to easily see their disk usage and monthly HTTP bandwidth consumption, until TextPanel provides the information.
The first time you use rsrcmeter, it may take additional time, as it will be scanning every Apache/HTTP log file for usage information and caching it by month.

--> Get Easy Install Instructions, Etc. at http://rsrcmeter.textjoy.com/.

Sample output:
Disk usage: 23.7227 MiB (Quota: 10.0000 GiB | 0.2% used)
Bandwidth:
Nov 2006: 0.5494 MiB (Month to Date)
Oct 2006: 0.5087 MiB
Sep 2006: 0.5523 MiB
Aug 2006: 1.1567 MiB


#!/usr/local/bin/ruby
# Unofficial TxD Disk & HTTP Bandwidth Usage Meter (rsrcmeter)
# Version 2.0.2
# Written by AJ Zmudosky
#
# THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND WITHOUT WARRANTY OF
# ANY KIND. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ANY
# DAMAGES HOWEVER CAUSED, AND ON ANY THEORY OF LIABILITY, ARISING IN ANY
# WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
# OF SUCH DAMAGE.

require 'date'
require 'optparse'

# E-mail regexp
module RFC2822
  EmailAddress = begin
    alpha = "a-zA-Z"
    digit = "0-9"
    atext = "[#{alpha}#{digit}\!\#\$\%\&\'\*+\/\=\?\^\_\`\{\|\}\~\-]"
    dot_atom_text = "#{atext}+([.]#{atext}*)*"
    dot_atom = "#{dot_atom_text}"
    qtext = '[^\\x0d\\x22\\x5c\\x80-\\xff]'
    text = "[\\x01-\\x09\\x11\\x12\\x14-\\x7f]"
    quoted_pair = "(\\x5c#{text})"
    qcontent = "(?:#{qtext}|#{quoted_pair})"
    quoted_string = "[\"]#{qcontent}+[\"]"
    atom = "#{atext}+"
    word = "(?:#{atom}|#{quoted_string})"
    obs_local_part = "#{word}([.]#{word})*"
    local_part = "(?:#{dot_atom}|#{quoted_string}|#{obs_local_part})"
    no_ws_ctl = "\\x01-\\x08\\x11\\x12\\x14-\\x1f\\x7f"   
    dtext = "[#{no_ws_ctl}\\x21-\\x5a\\x5e-\\x7e]"
    dcontent = "(?:#{dtext}|#{quoted_pair})"
    domain_literal = "\\[#{dcontent}+\\]"
    obs_domain = "#{atom}([.]#{atom})*"
    domain = "(?:#{dot_atom}|#{domain_literal}|#{obs_domain})"
    addr_spec = "#{local_part}\@#{domain}"
    pattern = /^#{addr_spec}$/
  end
end

# Default options
opt = {
  :base_dir => ENV['HOME'],
  :stat_file => 'histstat',
  :temp_file => 'temp-rsrcmeter-bwcalc',
  :bw_months => 5
}

# Our option flag parsing
OptionParser.new do |opts|
  opts.banner = "Unofficial TxD Disk & HTTP Bandwidth Usage Meter\nUsage: rsrcmeter [options]"
  
  opts.on("-b", "--base BASE", "Change the base directory, defaults to user's $HOME", String) {|base|
    if File.exists?(base)
      opt[:base_dir] = base
    else
      raise(ArgumentError, "Directory (#{base}) specified with -b does not exist")
    end
  }
  
  opts.on("--stat-file FILE", "Change default historical data file from '#{opt[:stat_file]}'", String) {|file|
    opt[:stat_file] = file
  }
  
  opts.on("--temp-file FILE", "Change default temporary file from '#{opt[:temp_file]}'", String) {|file|
    opt[:temp_file] = file
  }
  
  opts.on("-m NUM", "Number of months' bandwidth to show prior to current month (default: #{opt[:bw_months]})", Integer) {|mons|
    opt[:bw_months] = mons if mons > 0
  }
  
  opts.on("-e", "--email ADDRESS", "E-mail results to ADDRESS *instead* of outputting to the screen", String) {|addr|
    if RFC2822::EmailAddress =~ addr
      opt[:email_to] = addr
    else
      raise(ArgumentError, "Invalid e-mail address provided to -e")
    end
  }
  
  opts.on_tail("-h", "--help", "Show this message") do
    puts opts
    exit
  end
end.parse!

Dir.chdir(opt[:base_dir])
File.delete(opt[:temp_file]) if File.exists?(opt[:temp_file])

# Look for existing monthly statistics file
if File.exists?(opt[:stat_file])
  # Load and process existing stats
  @stats = Array.new
  lines = File.readlines(opt[:stat_file])
  lines.each {|l| (@stats << [l.chomp.split(',')[0], l.chomp.split(',')[1].to_f]) unless (l.strip)[0,1] == '#'}
  @stats.sort!
  # Determine if any months need to be added
  if Date.today.month == 1
    pm_year = Date.today.year - 1
    pm_month = 12
  else
    pm_year = Date.today.year
    pm_month = Date.today.month - 1
  end
  stop_month = pm_year.to_s + (pm_month < 10 ? '0' : '') + pm_month.to_s
  proc_year = @stats.last[0][0,4].to_i
  proc_month = @stats.last[0][4,2].to_i
  proc_year += 1 if proc_month == 12
  proc_month = (proc_month == 12) ? 1 : proc_month + 1
  proc_str = proc_year.to_s + (proc_month < 10 ? '0' : '') + proc_month.to_s
  # Add any months not already calculated
  while proc_str <= stop_month
    datestr = proc_str + "??"
    File.delete(opt[:temp_file]) if File.exists?(opt[:temp_file])
    `cat logs/access_log.#{datestr} 2>/dev/null > #{opt[:temp_file]}`
    `cat domains/*/logs/access_log.#{datestr} 2>/dev/null >> #{opt[:temp_file]}`
    `zcat logs/access_log.#{datestr}.gz 2>/dev/null >> #{opt[:temp_file]}`
    `zcat domains/*/logs/access_log.#{datestr}.gz 2>/dev/null >> #{opt[:temp_file]}`
    month_usage = `cat #{opt[:temp_file]} | awk '{sum += $10} END {print sum}'`.chomp.to_i
    @stats << [proc_str, month_usage]
    # advance counting
    proc_year += 1 if proc_month == 12
    proc_month = (proc_month == 12) ? 1 : proc_month + 1
    proc_str = proc_year.to_s + (proc_month < 10 ? '0' : '') + proc_month.to_s
  end
# Statistics files doesn't exist
else
  # Look for earliest log file
  file_list = Array.new
  Dir.foreach(opt[:base_dir] + "/logs") {|i| file_list << i if /^access_log.\d{8}/ =~ i}
  if File.exists?(opt[:base_dir] + "/domains")
    domains = Array.new
    Dir.foreach(opt[:base_dir] + "/domains") {|dom| domains << dom if /^\w+\.\w+/ =~ dom}
    domains.each {|dom| Dir.foreach(opt[:base_dir] + "/domains/" + dom + "/logs") {|i| file_list << i if /^access_log.\d{8}/  =~ i}}
  end
  file_list.sort!
  unless Date.today.year.to_s + Date.today.month.to_s == file_list.first[11,6]
    # Process from earliest_log year/month forward
    earliest_log_year = file_list.first[11,4]
    earliest_log_month = file_list.first[15,2]
    @stats = Array.new
    earliest_log_year.to_i.upto(Date.today.year) do |year|
      start_month = (earliest_log_year.to_i == year) ? earliest_log_month.to_i : 1;
      start_month.upto(12) do |month|
        unless (year == Date.today.year and month >= Date.today.month)
          month = "0" + month.to_s if month < 10
          datestr = year.to_s + month.to_s + '??'
          File.delete(opt[:temp_file]) if File.exists?(opt[:temp_file])
          `cat logs/access_log.#{datestr} 2>/dev/null > #{opt[:temp_file]}`
          `cat domains/*/logs/access_log.#{datestr} 2>/dev/null >> #{opt[:temp_file]}`
          `zcat logs/access_log.#{datestr}.gz 2>/dev/null >> #{opt[:temp_file]}`
          `zcat domains/*/logs/access_log.#{datestr}.gz 2>/dev/null >> #{opt[:temp_file]}`
          month_usage = `cat #{opt[:temp_file]} | awk '{sum += $10} END {print sum}'`.chomp.to_i
          @stats << [year.to_s + month.to_s, month_usage]
        end
      end
    end
  end
end

# Write @stats back to opt[:stat_file] to record any changes
File.open(opt[:stat_file], 'w') {|f|
  f.puts "# rsrcmeter historical statistics file"
  f.puts "# Contains only completed months"
  @stats.each {|i| f.puts i[0] + ',' + i[1].to_s}
}

# Calculate bandwidth consumption for current month
datestr = Date.today.year.to_s + Date.today.month.to_s + "??"
`cat logs/access_log 2>/dev/null > #{opt[:temp_file]}`
`cat domains/*/logs/access_log 2>/dev/null >> #{opt[:temp_file]}`
`cat logs/access_log.#{datestr} 2>/dev/null >> #{opt[:temp_file]}`
`cat domains/*/logs/access_log.#{datestr} 2>/dev/null >> #{opt[:temp_file]}`
`zcat logs/access_log.#{datestr}.gz 2>/dev/null >> #{opt[:temp_file]}`
`zcat domains/*/logs/access_log.#{datestr}.gz 2>/dev/null >> #{opt[:temp_file]}`
usage = `cat #{opt[:temp_file]} | awk '{sum += $10} END {print sum}'`.chomp.to_f / 1024 / 1024
File.delete(opt[:temp_file]) if File.exists?(opt[:temp_file])
# Determine disk usage
quotaline = `quota -g | tail -n 1`
disk_usage = `echo -n "#{quotaline}" | awk '{print $2}'`.to_f
disk_quota = `echo -n "#{quotaline}" | awk '{print $3}'`.to_f
disk_percent_used = (disk_usage / disk_quota) * 100

# Output results
results = ""
results << "Disk usage: " + sprintf("%.4f", disk_usage / 1024) + " MiB (Quota: " + sprintf("%.4f", disk_quota / 1024 / 1024) +" GiB | " + sprintf("%.1f", disk_percent_used) + "% used)\n"
results << "Bandwidth:\n" + Date::ABBR_MONTHNAMES[Date.today.month] + " " + Date.today.year.to_s + ": " + sprintf("%.4f", usage) + " MiB (Month to Date)\n"
hist_usage = @stats.last(opt[:bw_months]).reverse
hist_usage.each {|h| results << Date::ABBR_MONTHNAMES[Date.parse(h[0] + "01").month] + ' ' + h[0][0,4] + ": " + sprintf("%.4f", (h[1].to_f / 1024 / 1024)) + " MiB\n"}

# We're either e-mailing or outputting
if opt[:email_to]
  t = Time.now.strftime("%a %d %B %Y %H:%M:%S %Z")
  message = <<EOM
From: TxD Resource Meter <#{ENV['USER']}-noreply@#{`/bin/hostname`.chomp}>
To: #{opt[:email_to]}
Subject: [TxD Resource Meter] #{t} report for #{ENV['USER']}
X-Mailer: rsrcmeter | http://textsnippets.com/posts/show/842

Resource Report - #{t}
#{results}
---------------
Generated by rsrcmeter
EOM
  File.open("temp-emailresult", "w") { |file| file.print message }
  `cat temp-emailresult | /usr/sbin/sendmail -t`
  File.delete("temp-emailresult")
else
  puts results
end

create object fom underscore_syntax

// camelize - from underscore_syntax to Uppercas/ClassSyntax
// constantize - create instance
// (params[:property]) -- read data from web-form


    @property = property_type.camelize.constantize.new(params[:property])

Ruby Autoit script to handle javascript popups

Run this code to take care of any javascript popups or security confirmations. It will always click "OK".

require 'win32ole'

begin
  autoit = WIN32OLE.new('AutoItX3.Control')
    
  loop do
   autoit.ControlClick("Microsoft Internet Explorer",'', 'OK')
   autoit.ControlClick("Security Information",'', '&Yes')
   autoit.ControlClick("Security Alert",'', '&Yes')
   sleep(5)
  end
       
rescue Exception => e
  puts e
end


If you are using this as part of a script, you can include it using this structure.

require 'win32/process'

  @pid = Process.create(
          :app_name       => 'ruby clicker.rb', #assuming you make the above script into a file called clicker.rb
          :creation_flags  => Process::DETACHED_PROCESS
      ).process_id
     
at_exit{ Process.kill(9,@pid) }

get url / uri in *.rhtml file

// find out the current url / uri in *.rhtml file
// is quite simple with the request object
<% page = request.request_uri %>
page: <%= page %>


// or when different urls mean the same page
<% page = "/" + request.path_parameters['controller'] + "/" + request.path_parameters['action'] %>
page: <%= page %>
« Newer Snippets
Older Snippets »
Showing 41-60 of 128 total