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 »
127 total  XML / RSS feed 

lazy initialized boolean ruby 1.8.6

// lazily initialize a boolean accessor (requires ruby > 1.8.6)

  def attr?
    @attr = true unless instance_variable_defined? :@attr
    @attr
  end

HTML stripper

// description of your code here

str = <<HTML_TEXT



  

Application error

Change this error message for exceptions thrown outside of an action (like in Dispatcher setups or broken Ruby code) in public/500.html

HTML_TEXT puts str.gsub(/<\/?[^>]*>/, "")

Ubuntu 7.10: bootstrap a Ruby on Rails stack

// get started with ubuntu 7.1
// e.g. on a new slice from http://slicehost.com !

# 1) make yrself a user and stop being root

# 2) main web stack + ruby
sudo aptitude install -y make screen
sudo aptitude install -y apache2 php5 mysql-server
sudo aptitude install -y subversion postfix
sudo aptitude install -y ruby1.8 ruby1.8-dev rubygems irb
sudo aptitude install -y imagemagick librmagick-ruby1.8 librmagick-ruby-doc libfreetype6-dev xml-core

# 3) gemz
# rubygems appears to be broken as hell. 
# gem update --system does squat
# had to manually d/l rubygems 1.0.1, ruby setup.rb
wget http://rubyforge.org/frs/download.php/29548/rubygems-1.0.1.tgz
tar xzvf rubygems-1.0.1.tgz
cd rubygems-1.0.1
sudo ruby setup.rb
sudo gem install rails mongrel merb map_by_method


Scrape torrents on btjunkie

// download all .torrent links on the btjunkie frontpage
//
// more fun with mechanize @
// http://tramchase.com/scrape-myspace-youtube-torrents-for-fun-and-profit

agent = WWW::Mechanize.new
agent.get("http://btjunkie.org/")
links = agent.page.search('.tor_details tr a')
hrefs = links.map { |m| m['href'] }.select { |u| u =~ /\.torrent$/ } # just links ending in .torrent
FileUtils.mkdir_p('btjunkie-torrents') # keep it neat
hrefs.each { |torrent|
  filename = "btjunkie-torrents/#{torrent[0].split('/')[-2]}"
  puts "Saving #{torrent} as #{filename}"
  agent.get(torrent).save_as(filename)
}

Scrape MySpace friend thumbnails

// fetch all img's from a myspace profile's .friendSpace div
// more @ http://tramchase.com/scrape-myspace-youtube-torrents-for-fun-and-profit

agent = WWW::Mechanize.new
agent.get("http://myspace.com/graffitiresearchlab")
links = agent.page.search('.friendSpace img') # found w/ firebug
FileUtils.mkdir_p 'myspace-images' # make the images dir
links.each_with_index { |link, index| 
  url = link['src']
  puts "Saving thumbnail #{url}"
  agent.get(url).save_as("myspace-images/top_friend#{index}_#{File.basename url}")
}

Scrape YouTube thumbnails

// fun with mechanize
// more @ http://tramchase.com/scrape-myspace-youtube-torrents-for-fun-and-profit

agent = WWW::Mechanize.new
url = "http://gdata.youtube.com/feeds/api/standardfeeds/most_viewed" # all time
page = agent.get(url)
# parse again w/ Hpcricot for some XML convenience
doc = Hpricot.parse(page.body)
# pp (doc/:entry) # like "search"; cool division overload
images = (doc/'media:thumbnail') # use strings instead of symbols for namespaces
FileUtils.mkdir_p 'youtube-images' # make the images dir
urls = images.map { |i| i[:url] }
urls.each_with_index do |file,index|
  puts "Saving image #{file}"
  agent.get(file).save_as("youtube-images/vid#{index}_#{File.basename file}")
end

jQuery and Rails' respond_to

// Just throw this at the bottom of your application.js and you’re good to go: all jQuery ajax requests will trigger the wants.js block of your respond_to declaration, exactly like you’d expect. Enjoy.
// via: http://ozmm.org/posts/jquery_and_respond_to.html

jQuery.ajaxSetup({beforeSend’: function(xhr) {xhr.setRequestHeader(“Accept”,text/javascript”)} })

writing destructive string methods in Ruby

Use string class' method "replace" to overwrite its "self" value.

Example:

  def decapitalize!
    replace (self.reverse.chop + self.reverse.last.downcase).reverse
  end
  
  def decapitalize
    dup.decapitalize!
  end

simple Ruby RSS reader

// fetch & parse RSS into an object

require 'rss/2.0'
require 'open-uri'

class RssReader

  def parseFeed (url, length)
    feed_url = url
    output = "";
    open(feed_url) do |http|
      response = http.read
      result = RSS::Parser.parse(response, false)
      output = "\"feedTitle\">#{result.channel.title}
" end return output end end

acts_as_state_machine model

// ActiveRecord plugin for managing state changes
// elitists.textdriven.com/svn/plugins/acts_as_state_machine/

class Something < ActiveRecord::Base

  # Validations
  validate :validate_state_change

  # State Machine States
  acts_as_state_machine :initial => :new
  state :new
  state :enabled,   :after => :after_enabled
  state :disabled,  :after => :after_disabled

  # State Machine Events
  event :enabled do
    transitions :from => :new,      :to => :enabled
    transitions :from => :disabled, :to => :enabled
  end
  
  event :disabled do
    transitions :from => :new,      :to => :disabled
    transitions :from => :enabled,  :to => :disabled
  end

  # Instance Methods
  def validate_state_change
    return if new_record?
    old = self.class.find(id)
    old_state = old.state
    new_state = self.state
    self.state = old_state
    if old_state != new_state
      begin
        if self.method("#{new_state}!").call != true
          errors.add(:state, "cannot transition from #{old_state} to #{new_state}")
        end
      rescue NameError
      end
      self.state = new_state
    end
  end
end

Enumerable vs. Enumerator. Standard Library vs. Core Library in Ruby.

Rdoc is causing some serious confusion with libraries.

In core documentation, Enumerable defines each_slice method.

Extend this module into your class and each_slice is not defined.

Reason? each_slice is NOT in the core Enumerable module, but rather the Standard Library Enumerable::Enumerator class, even though the ruby-doc core class documents say otherwise.

You must

require 'enumerator'


to have each_slice is available as a method to your classes.

Benchmark methods

Here we define two ways to process chunks of Array elements at a time.

Below we define a benchmarking test using a double run, one as a preliminary run, one as a real test run.

class Array
  def process(method_obj, batch_size = 10, fin = [])
    if (this_batch = self.first(batch_size)).size > 0
      fin.concat method_obj.call(this_batch)
      (self - this_batch).process(method_obj, batch_size, fin)
    else
      return fin
    end
  end
  
  def proc_array(method_obj, batch_size = 2)
    result = []
    self.each_slice(batch_size) do |batch|
      result.concat method_obj.call(batch)
    end
    result
  end
end

def munge(ary)
  ary.collect { |e| e.+ 10 }
end

my_meth = method(:munge)

BIGARY = Array.new(100) {|i| i}

require 'benchmark'
include Benchmark

bmbm(2) do |test|
  test.report("recursive") do
    10000.times {BIGARY.process(my_meth, 2)}
  end
  test.report("block") do
    10000.times {BIGARY.proc_array(my_meth)}
  end
end

reload modules and files in irb

To reload a changed module, class, etc. file in ruby irb:

load 'filename.rb'


The extension is required in this case

running single test case with ruby testunit

Run only a single test case within your testing file

ruby my_testing_file.rb --name test_casename

irb ruby test case testing

When building test cases for testing ruby classes and modules you can use irb to test your test cases.

require the test/unit files
then include the Test::Unit::Assertions module

load irb from the terminal
require 'test/unit'
include Test::Unit::Assertions


At this point you can use all assertions available through the Assertions module.

Read / Write attributes not keeping value

If a writeable attribute is not keeping its assigned value, check that the write method is using
self.<attribute> = val

, not just
<attribute> = val


Ruby is thinking that = is a local assignment operation, not an assignment of a writeable attribute.

include vs. extend in Ruby

There are multiple ways of extending the functionality of a class in Ruby.
One way is to 'include' a module in a ruby class definition.

class Billy
  include Bully
end

This brings all methods defined in module 'Bully' into Billy as instance methods.

Another way is to 'extend' a class definition with a module
class Billy
  extend Bully
end
Billy.fight(others)

This brings in the methods defined in Bully module, but as class methods

Every object in Ruby implements the 'extend' method. This allows you to extend a class' functionality within an instance through using 'extend'. The module methods brought in are available as instance methods (as compared to using 'extend' within a class definition).
a = Billy.new()
a.extend Bully
a.fight(weaklings)

MIME to icon mapping

// description of your code here

@@mime_to_icon_map = {
  'default' => 'default',
   
  'text/' => 'text',
  'text/html' => 'html',
  'application/rtf' => 'rtf',
   
  'application/pdf' => 'pdf',
  'application/bzpdf' => 'pdf',
  'application/gzpdf' => 'pdf',
  'application/postscript' => 'pdf',
   
  'text/spreadsheet' => 'spreadsheet',
  'application/gnumeric' => 'spreadsheet',
  'application/kspread' => 'spreadsheet',
       
  'application/scribus' => 'doc',
  'application/abiword' => 'doc',
  'application/kword' => 'doc',
           
  'application/msword' => 'msword',
  'application/mswrite' => 'msword',
  'application/vnd.ms-powerpoint' => 'mspowerpoint',
  'application/vnd.ms-excel' => 'msexcel',
  'application/vnd.ms-access' => 'msaccess',
   
  'application/executable' => 'binary',
  'application/ms-dos-executable' => 'binary',
  'application/octet-stream' => 'binary',
   
  'application/shellscript' => 'shell',
  'application/ruby' => 'ruby',
       
  'application/vnd.oasis.opendocument.spreadsheet' => 'oo-spreadsheet',   
  'application/vnd.oasis.opendocument.spreadsheet-template' => 'oo-spreadsheet',
  'application/vnd.oasis.opendocument.formula' => 'oo-spreadsheet',
  'application/vnd.oasis.opendocument.chart' => 'oo-spreadsheet',
  'application/vnd.oasis.opendocument.image' => 'oo-graphics',   
  'application/vnd.oasis.opendocument.graphics' => 'oo-graphics',
  'application/vnd.oasis.opendocument.graphics-template' => 'oo-graphics',
  'application/vnd.oasis.opendocument.presentation-template' => 'oo-presentation',
  'application/vnd.oasis.opendocument.presentation' => 'oo-presentation',
  'application/vnd.oasis.opendocument.database' => 'oo-database',
  'application/vnd.oasis.opendocument.text-web' => 'oo-html',
  'application/vnd.oasis.opendocument.text' => 'oo-text',
  'application/vnd.oasis.opendocument.text-template' => 'oo-text',
  'application/vnd.oasis.opendocument.text-master' => 'oo-text',
   
  'packages/' => 'archive',
  'application/zip' => 'archive',
  'application/gzip' => 'archive',
  'application/rar' => 'archive',
  'application/deb' => 'archive',
  'application/tar' => 'archive',
  'application/stuffit' => 'archive',
  'application/compress' => 'archive',
               
   'video/' => 'video',

   'audio/' => 'audio',
   
   'image/' => 'image',
   'image/svg+xml' => 'vector',
   'image/svg+xml-compressed' => 'vector',
   'application/illustrator' => 'vector',
   'image/bzeps' => 'vector',
   'image/eps' => 'vector',
   'image/gzeps' => 'vector',
  
   'application/pgp-encrypted' => 'lock',
   'application/pgp-signature' => 'lock',
   'application/pgp-keys' => 'lock'
} 

Capistrano task to load production data

# load production data, still needs some polish
# based on code from http://push.cx/2007/capistrano-task-to-load-production-data
# cap 2.0 compatible
# exec is being weird, had to end w/ a syscall :\ any ideas?

desc "Load production data into development database"
task :load_production_data, :roles => :db, :only => { :primary => true } do
  require 'yaml'
  ['config/database.yml'].each do |file|

    database = YAML::load_file(file)

    filename = "dump.#{Time.now.strftime '%Y-%m-%d_%H:%M:%S'}.sql.gz"
    # on_rollback { delete "/tmp/#{filename}" }

    # run "mysqldump -u #{database['production']['username']} --password=#{database['production']['password']} #{database['production']['database']} > /tmp/#{filename}" do |channel, stream, data|
    run "mysqldump -h #{database['production']['host']} -u #{database['production']['username']} --password=#{database['production']['password']} #{database['production']['database']} | gzip > /tmp/#{filename}" do |channel, stream, data|
      puts data
    end
    get "/tmp/#{filename}", filename
    # exec "/tmp/#{filename}"
    password = database['development']['password'].nil? ? '' : "--password=#{database['development']['password']}"  # FIXME pass shows up in process list, do not use in shared hosting!!! Use a .my.cnf instead
    # FIXME exec and run w/ localhost as host not working :\
    # exec "mysql -u #{database['development']['username']} #{password} #{database['development']['database']} < #{filename}; rm -f #{filename}"
    `gunzip -c #{filename} | mysql -u #{database['development']['username']} #{password} #{database['development']['database']} && rm -f gunzip #{filename}`
  end
  
end

Сортировка массива с городами

// К примеру мне нужен массив с городами(имя, год основания). Отсортировать его(по году основания) и вывести названия городов.
// Чтобы отсортировать массив по населению, надо лишь заменить year на population)

cities = Array.new
cities << { :name => 'SPb',    :year => 1703, :population => 5_000_000 }
cities << { :name => 'Moscow', :year => 1147, :population => 10_000_000_000 }

cities.sort_by { |city| city[:year] }.each do |city|
  puts "#{city[:name]}"
end
« Newer Snippets
Older Snippets »
127 total  XML / RSS feed