Author: dr_bob
require 'pp'
tree = (cr = lambda {h,k h[k] = Hash.new &cr})[{},nil]
ObjectSpace.each_object(Class) {cl if cl.ancestors.include? Exception
then cl.ancestors.reverse.inject(tree){tr,cl tr[cl]} end}
pp tree
23 Ağustos 2007 Perşembe
Print Exception Class Hieararchy
Extend Float and FixNum to do calculations in S.I. units
Source: 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
Extend String to use ActionView's Text Helpers
Author: curtissummers, http://www.csummers.org/index.php/2006/08/07/extend-string-to-use-actionviews-text-helpers/
#ActionView's TextHelper methods are useful, but I often need to use them in my controller or my model. For several of the TextHelper methods that expect a string as input, it makes sense to extend the String class.
#So, if I want to strip HTML tags, auto link any URLs, and then simple format a comment (in that order) before I save it in the database I can do:
class Comment < ActiveRecord::Base
#...
def before_save
self.text = self.text.strip_tags.auto_link.simple_format
end
end
# This method is much cleaner than including ActionView::Helpers::TextHelper in whatever class I'm in and passing the string as an argument to each method.
# Below is the magic code. Since TextHelper is a module, we create a Singleton class to reference the methods, create the wrapper methods in their own module, and finally include that module in the String class. Note that not all TextHelper methods are included–just the ones that make sense. Drop this code into a file and require it in your environment or within a plugin.
# ActionView Text Helpers are great!
# Let's extend the String class to allow us to call
# some of these methods directly on a String.
# Note:
# - cycle-related methods are not included
# - concat is not included
# - pluralize is not included because it is in
# ActiveSupport String extensions already
# (though they differ).
# - markdown requires BlueCloth
# - textilize methods require RedCloth
# Example:
# "<b>coolness</b>".strip_tags -> "coolness"
require 'singleton'
# Singleton to be called in wrapper module
class TextHelperSingleton
include Singleton
include ActionView::Helpers::TextHelper
include ActionView::Helpers::TagHelper #tag_options needed by auto_link
end
# Wrapper module
module MyExtensions #:nodoc:
module CoreExtensions #:nodoc:
module String #:nodoc:
module TextHelper
def auto_link(link = :all, href_options = {}, &block)
TextHelperSingleton.instance.auto_link(self, link, href_options, &block)
end
def excerpt(phrase, radius = 100, excerpt_string = "…")
TextHelperSingleton.instance.excerpt(self, phrase, radius, excerpt_string)
end
def highlight(phrase, highlighter = '<strong class="highlight">\1</strong>')
TextHelperSingleton.instance.highlight(self, phrase, highlighter)
end
begin
require_library_or_gem 'bluecloth'
def markdown
TextHelperSingleton.instance.markdown(self)
end
rescue LoadError
# do nothing. method will be undefined
end
def sanitize
TextHelperSingleton.instance.sanitize(self)
end
def simple_format
TextHelperSingleton.instance.simple_format(self)
end
def strip_tags
TextHelperSingleton.instance.strip_tags(self)
end
begin
require_library_or_gem 'redcloth'
def textilize
TextHelperSingleton.instance.textilize(self)
end
def textilize_without_paragraph
TextHelperSingleton.instance.textilize_without_paragraph(self)
end
rescue LoadError
# do nothing. methods will be undefined
end
def truncate(length = 30, truncate_string = "…")
TextHelperSingleton.instance.truncate(self, length, truncate_string)
end
def word_wrap(line_width = 80)
TextHelperSingleton.instance.word_wrap(self, line_width)
end
end
end
end
end
# extend String with the TextHelper functions
class String #:nodoc:
include MyExtensions::CoreExtensions::String::TextHelper
end
Full text searching for ri content
Author: zenspider, http://blog.zenspider.com/archives/2006/08/full_text_searc.html
#From ZenSpider, http://blog.zenspider.com/archives/2006/08/full_text_searc.html:
#Check it out. Quick and dirty searching of ri content:
#Updated using: http://blog.zenspider.com/archives/2006/08/new_and_improve.html
# They added path independence and searching of gems and local installed ri/rdoc. Enjoy!#!/usr/local/bin/ruby -w
require 'rdoc/ri/ri_paths'
require 'find'
require 'yaml'
search = ARGV.shift
puts "Searching for #{search}"
puts
dirs = RI::Paths::PATH
dirs.each do dir
Dir.chdir dir do
Find.find('.') do path
next unless test ?f, path
yaml = File.read path
if yaml =~ /#{search}/io then
full_name = $1 if yaml[/full_name: (.*)/]
puts "** FOUND IN: #{full_name}"
data = YAML.load yaml.gsub(/ \!.*/, '')
desc = data['comment'].map { x x.values }.flatten.join("\n").gsub(/"/, "'").gsub(/</, "<").gsub(/>/, ">").gsub(/&/, "&")
puts
puts desc
puts
end
end
end
end
# Lets you do stuff like:
% ./risearch.rb duplicate
# Searching for duplicate
[...]
** FOUND IN: Array#uniq!
# Removes duplicate elements from self. Returns nil if no changes are made (that is, no duplicates are found).
a = [ 'a', 'a', 'b', 'b', 'c' ]
a.uniq! #=> ['a', 'b', 'c']
b = [ 'a', 'b', 'c' ]
b.uniq! #=> nil
** FOUND IN: Array#
# Set Union---Returns a new array by joining this array with other_array, removing duplicates.
[ 'a', 'b', 'c' ] [ 'c', 'd', 'a' ]
#=> [ 'a', 'b', 'c', 'd' ]
[...]
Load a Web page in Ruby and print information
Author: jswizard , 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
13 Ağustos 2007 Pazartesi
Recursive program to compute n!
def factorial(n)
if n == 0
return 1
else
return n * factorial(n - 1)
end
end
Full information for Ruby errors
#author: ciconia , http://www.bigbold.com/snippets/user/ciconia/2
#Sometimes I want to be able to print out everything about an error: it's class, message and the stack trace. So how about this:
#Update: followed suggestion by onarap and changed the line breaks to $/. No syntax highlighting because the code breaks the snippet parser.
class StandardError
def info
"#{self.class}: #{message}#$/#{backtrace.join($/)}"
end
end
Create classes at runtime
#author: nicwilliams , http://drnicwilliams.com/2006/08/07/ann-dr-nics-magic-models/
#For example, if you want to create a new class at runtime, and assign it a superclass, try the following:
def create_class(class_name, superclass, &block)
klass = Class.new superclass, &block
Object.const_set class_name, klass
end
With this code, you can create a class as follows:
create_class('Person', ActiveRecord::Base) do
set_table_name :people
def fullname
"#{firstname} #{lastname}" # assuming the people table has firstname,lastname columns
end
end
Nice post slug
#author: sligowaths http://www.bigbold.com/snippets/user/sligowaths/2
#-------------------------------------------------------------------------
#This code replaces accents to normal chars(e.g "á" => "a"), everything that isn´t in "a-zA-Z0-9" to "", multiples spaces to one space, and one space to "-".
#This is useful to make URLs from titles, like Netscape.com does...
#"A new report recommends only work 4 -6 hrs a day" => #"A-new-report-recommends-only-work-4-6-hrs-a-day"
#"Video: \"Popular Mechanics\" editor debunks 9/11 myths" => "Video-Popular-Mechanics-editor-debunks-911-myths"
# etc..
# The code is 95% based on http://textsnippets.com/posts/show/451
def self.nice_slug(str)
accents = {
['á','à','â','ä','ã'] => 'a',
['Ã','Ä','Â','À','Á'] => 'A',
['é','è','ê','ë'] => 'e',
['Ë','É','È','Ê'] => 'E',
['í','ì','î','ï'] => 'i',
['Í','Î','Ì','Ï'] => 'I',
['ó','ò','ô','ö','õ'] => 'o',
['Õ','Ö','Ô','Ò','Ó'] => 'O',
['ú','ù','û','ü'] => 'u',
['Ú','Û','Ù','Ü'] => 'U',
['ç'] => 'c', ['Ç'] => 'C',
['ñ'] => 'n', ['Ñ'] => 'N'
}
accents.each do ac,rep
ac.each do s
str = str.gsub(s, rep)
end
end
str = str.gsub(/[^a-zA-Z0-9 ]/,"")
str = str.gsub(/[ ]+/," ")
str = str.gsub(/ /,"-")
#str = str.downcase
end
Simple "Send Email from Ruby" Method
author: Peter (Ian Purton)
----------------------------
def send_email(from, from_alias, to, to_alias, subject, message)
msg = <<END_OF_MESSAGE
From: #{from_alias} <#{from}>
To: #{to_alias} <#{to}>
Subject: #{subject}
#{message}
END_OF_MESSAGE
Net::SMTP.start('localhost') do smtp
smtp.send_message msg, from, to
end
end
12 Ağustos 2007 Pazar
Rake tasks to sync project hosted on freeonrails
// rake tasks to sync project hosted on freeonrails
require File.dirname(__FILE__) + "/scp_wrapper"
desc "pushes the app files onto freeonrails"
task :update_freeonrails => :environment do t
scp_wrapper = ScpWrapper.new
scp_wrapper.update_code
scp_wrapper.update_db
scp_wrapper.update_javascript
scp_wrapper.update_css
scp_wrapper.update_tests
# scp_wrapper.images
end
// ha .. moved over to rsync last moment
class ScpWrapper
def update_code
sync "app"
end
def update_db
sync "db/migrate", "db"
end
def update_javascript
sync "public/javascripts", "public"
end
def update_css
sync "public/stylesheets", "public"
end
def update_tests
sync "test"
end
def images
sync "public/images", "public"
end
private
def sync(source, dest = "")
system "rsync -avz #{RAILS_ROOT}/#{source} biketw@biketowork.info:/home/biketw/btw/#{dest}"
puts "#{source} synched"
endend
Simple enum creation
module Kernel
# simple (sequential) enumerated values
def enum(*syms)
syms.each { s const_set(s, s.to_s) }
const_set(:DEFAULT, syms.first) unless syms.nil?
end
end
//and the usage
require 'kernel'
module Constants
module Gradient
enum :DOWNSLOPE, :LEVEL, :UPSLOPE
end
module TreeCover
enum :GOOD, :BAD, :OK
end
module TrafficDensity
enum :LOW, :MEDIUM, :HIGH
end
end
11 Ağustos 2007 Cumartesi
Building drop down boxes using enum generated Constants
require 'constants'
module MapHelper
LOCAL_KEY =
FREE_ON_RAILS_KEY =
def key
case `hostname`.chomp
when 'localhost', 'rohan'
LOCAL_KEY
else
FREE_ON_RAILS_KEY
end
end
def tree_cover
build_options Constants::TreeCover
end
def gradient
build_options Constants::Gradient
end
def traffic_density
build_options Constants::TrafficDensity
end
def default(method)
eval "Constants::#{method}::DEFAULT"
end
private
def build_options(sym)
sym.constants.inject("") {str, value str + wrap(value) }
end
def wrap(option)
"<option value='#{option}'> #{option.downcase.capitalize} </option>"
end
end
// and the tests for this
require File.dirname(__FILE__) + '/../test_helper'
class MapHelperTest < Test::Unit::TestCase
include MapHelper
def test_options_for_combo_box_are_built_correctly
assert_tree_cover :GOOD
assert_gradient :DOWNSLOPE
assert_traffic_density :LOW
end
def test_defaulting
assert_default :TreeCover, :GOOD
assert_default :Gradient, :DOWNSLOPE
assert_default :TrafficDensity, :LOW
end
def assert_default(subject, const)
assert_equal const, default(subject)
end
def assert_tree_cover(const)
const = const.to_s
assert tree_cover.include?(option_string(const))
end
def assert_gradient(const)
const = const.to_s
assert gradient.include?(option_string(const))
end
def assert_traffic_density(const)
const = const.to_s
assert traffic_density.include?(option_string(const))
end
def option_string(const)
"<option value='#{const}'> #{const.downcase.capitalize} </option>"
end
end
Fix for ActiveRecord SQL Server adapter dates
# The SQL Server adapter for ActiveRecord uses Time objects to cast dates from the db. This fails for dates before 1970, thus some birthdates come back as nil. This is some kludge to use a DateTime in that case so we still get the value.
# A better approach may be to convert this code to use DateTime objects exclusively, but I'm not sure of the speed implications of doing so. The code below first tries to cast the value to a Time object; if that fails, it tries a DateTime object; if that fails, it returns nil.
# Stick this in a plugin to use with Rails.
module ActiveRecord
module ConnectionAdapters
class ColumnWithIdentity
def cast_to_time(value)
return value if value.is_a?(Time) or value.is_a?(DateTime)
time_array = ParseDate.parsedate(value)
time_array[0] = 2000
time_array[1] = 1
time_array[2] = 1
Time.send(Base.default_timezone, *time_array) rescue DateTime.new(*time_array[0..5]) rescue nil
end
def cast_to_datetime(value)
if value.is_a?(Time) or value.is_a?(DateTime)
if value.year != 0 and value.month != 0 and value.day != 0
return value
else
return Time.mktime(2000, 1, 1, value.hour, value.min, value.sec) rescue nil
end
end
return cast_to_time(value) if value.is_a?(Date) or value.is_a?(String) rescue nil
value
end
end
end
end
Read and parse RSS feed
require 'open-uri'
require 'rss/0.9'
require 'rss/1.0'
require 'rss/2.0'
require 'rss/parser'
url = 'http://some.host/rss.xml'
rss = RSS::Parser.parse(open(url){fdfd.read})
puts rss.items.collect{itemitem.title}.join("\n")
Displaying the last 10 pages visited from a session
# I wanted to store and display an array of the last 10 visited pages in a session. With the help of some folks in #rubyonrails (particularly aqua) this is what i've come up with:
class ApplicationController < ActionController::Base
before_filter :add_to_history
before_filter :page_title def add_to_history
session[:history] = []
session[:history].unshift ({"url" => @request.request_uri, "name" => page_title })
session[:history].pop while session[:history].length > 11
end
# This bit came from Peter Cooper's snippets source and was moved into the application controller: def page_title
case self.controller_name
when 'tag'
title = "Tags » " + @params[:tags].join(" > ")
when 'user'
title = "Users » #{@params[:user]}"
when 'features'
case self.action_name
when 'show' then title = "Feature » #{Feature.find(@params[:id]).title}"
else title = APP_CONFIG["default_title"]
end
else
title = APP_CONFIG["default_title"] + self.controller_name + ":" + self.action_name
end
end
helper_method :page_title...
end
# In your partial you might do something like this:
<h4>User History</h4>
<% for cur in session[:history][0..9] -%>
<p><a href="<%= cur["url"] %>"><%= cur["name"] %></a></p>
<% end -%>
9 Ağustos 2007 Perşembe
Dummy File Generator
// This file generates a dummy file specified to your size.
#!c:/ruby/bin/ruby
require 'scanf'
print 'Enter file size (mb):'
a = scanf('%d')
thesize = a[0]
print 'You ordered a ' + thesize.to_s + ' MB file.'
# Generate the file
string = "abcdefghijklmnopqrstuvwxyz1234567890"
filesize = 0;
f = File.new(thesize.to_s + 'MB', 'w')
while filesize < thesize * 1e6
f.puts string
filesize += string.size
end
f.close
Detect if your running on windows
## It's an unfortunate necessity that you need to write different code for windows sometimes or at the very least load different libraries since there is no fork(), etc. This is how you can tell.
# Returns true if we are running on a MS windows platform, false otherwise.
def Kernel.is_windows?
processor, platform, *rest = RUBY_PLATFORM.split("-")
platform == 'mswin32'
end
Random Alphanumeric String Generator
## This allows you to do String.random_alphanumeric(num) to get a random string that is num characters long. Useful for generating random identifier keys.
# Returns a random alphanumeric string of arbitrary size.
def String.random_alphanumeric(size=16)
s = ""
size.times { s << (i = Kernel.rand(62); i += ((i < 10) ? 48 : ((i < 36) ? 55 : 61 ))).chr }
s
end
Color Picker drop-down box helper
// description of your code here
//This helper will generate a whole bunch o' colors in a drop down box, which which you can do whatever with. Currently I am allowing users to change certain colors of the page.
def color_picker(name)
#build the hexes
hexes = []
(0..15).step(3) do |one|
(0..15).step(3) do |two|
(0..15).step(3) do |three|
hexes << "#" + one.to_s(16) + two.to_s(16) + three.to_s(16)
end
end
end
arr = []
10.times { arr << " " }
returning html = '' do
html << "<select name=#{name}>"
html << hexes.collect {|c|
"<option value='#{c}' style='background-color: #{c}'>#{arr.join}</option>" }.join("\n")
html << "</select>"
end
end