Never been to CodeSnippets 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!)

Use Tweetstream in Ruby

// description of your code here

Successfully installed yajl-ruby-0.6.3
Successfully installed daemons-1.0.10
Successfully installed intridea-tweetstream-0.1.3
3 gems installed
Installing ri documentation for yajl-ruby-0.6.3...
Installing ri documentation for daemons-1.0.10...
Installing RDoc documentation for yajl-ruby-0.6.3...
Installing RDoc documentation for daemons-1.0.10...


require 'rubygems'
require 'tweetstream'

user, pass = 'jrobertson', 'secret'
TweetStream::Client.new(user,pass).sample do |status|
  puts "[#{status.user.screen_name}] #{status.text}" 
  sleep 0.5
end

Deep' in Ruby

// description of your code here

#!/usr/local/bin/ruby

##!/opt/local/bin/ruby1.9

# Update Ruby via MacPorts:
# port info ruby19
# sudo port install ruby19


# See:
# - Tailin' Ruby, http://judofyr.net/posts/tailin-ruby.html
# - Re: Ruby and recursion (Ackermann benchmark), http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/145593

class Class
  # Sweet stuff!
  def tailcall_optimize( *methods )
    methods.each do |meth|
      org = instance_method( meth )
      define_method( meth ) do |*args|
        if Thread.current[ meth ]
          throw( :recurse, args )
        else
          Thread.current[ meth ] = org.bind( self )
          result = catch( :done ) do
            loop do
              args = catch( :recurse ) do
                throw( :done, Thread.current[ meth ].call( *args ) )
              end
            end
          end
          Thread.current[ meth ] = nil
          result
        end
      end
    end
  end
end



# tail-call optimization test

# example 1

class TCOTest
  # tail-recursive factorial
  def fact( n, acc = 1 )
    if n < 2 then acc else fact( n-1, n*acc ) end
  end

  # length of factorial
  def fact_size( n )
    fact( n ).size
  rescue
    $!
  end   
end

t = TCOTest.new

# normal method
puts t.fact_size( 10000 )  # => stack level too deep

# enable tail-call optimization
class TCOTest
  tailcall_optimize :fact
end

# tail-call optimized method
puts t.fact_size( 10000 )  # => 14808                                  


# example 2

class TCOTest2
   def addnum(i) 
      p i
      addnum(i+1) 
   end
end


#TCOTest2.new.addnum 0   # stack level too deep (SystemStackError)

# enable tail-call optimization
class TCOTest2
  tailcall_optimize :addnum
end

TCOTest2.new.addnum 0

Selected Code

// description of your code here

/// <summary>
    /// Selected Items Facade
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class Selected<T>
    {
        /// <summary>
        /// Gets selected items as T from the specified list box.
        /// </summary>
        /// <param name="listBox">The list box.</param>
        /// <returns></returns>
        public static IEnumerable<T> From(ListBox listBox)
        {
            List<T> result = new List<T>();

            foreach (T item in listBox.SelectedItems)
            {
                result.Add(item);
            }

            return result;
        }

        /// <summary>
        /// Gets selected item as T from the specified combo box.
        /// </summary>
        /// <param name="comboBox">The combo box.</param>
        /// <returns></returns>
        public static T From(ComboBox comboBox)
        {
            return comboBox.SelectedIndex > -1
                       ? (T) comboBox.Items[comboBox.SelectedIndex]
                       : default(T);
        }
    }

To aligh text in SVG apply the text-align style within the text style attribute

// description of your code here

<g
   inkscape:label="Layer 1"
   inkscape:groupmode="layer"
   id="layer1">
  <rect
     style="fill:#ff3700;fill-opacity:1"
     id="rect2888"
     width="52.468475"
     height="2.3319323"
     x="94.312019"
     y="57.362206" />
  <text
     xml:space="preserve"
     style="font-size:13.05882072px;font-style:normal;font-weight:normal;text-align:start;line-height:125%;writing-mode:lr-tb;text-anchor:start;fill:#000000;fill-opacity:1;stroke:none;font-family:Bitstream Vera Sans"
     x="94.043755"
     y="76.981842"
     id="text2884-8"
     sodipodi:linespacing="125%"><tspan
       sodipodi:role="line"
       id="tspan2886-0"
       x="94.043755"
       y="76.981842">text07</tspan></text>
  <rect
     style="fill:#ff3700;fill-opacity:1"
     id="rect2888-3"
     width="52.468475"
     height="2.3319323"
     x="94.312019"
     y="83.013474" />

  <rect
     style="fill:#ff3700;fill-opacity:1"
     id="rect2888-5"
     width="52.468475"
     height="2.3319323"
     x="94.312019"
     y="108.6647" />
  <rect
     style="fill:#ff3700;fill-opacity:1"
     id="rect2888-1"
     width="52.468475"
     height="2.3319323"
     x="94.312019"
     y="134.31596" />
  <text
     xml:space="preserve"
     style="font-size:13.05882072px;font-style:normal;font-weight:normal;text-align:center;line-height:125%;writing-mode:lr-tb;text-anchor:middle;fill:#000000;fill-opacity:1;stroke:none;font-family:Bitstream Vera Sans"
     x="94.043755"
     y="102.34161"
     id="text2884-8-1"
     sodipodi:linespacing="125%"><tspan
       sodipodi:role="line"
       id="tspan2886-0-3"
       x="94.043755"
       y="102.34161">text07</tspan></text>
  <text
     xml:space="preserve"
     style="font-size:13.05882072px;font-style:normal;font-weight:normal;text-align:end;line-height:125%;writing-mode:lr-tb;text-anchor:end;fill:#000000;fill-opacity:1;stroke:none;font-family:Bitstream Vera Sans"
     x="94.043755"
     y="127.70137"
     id="text2884-8-3"
     sodipodi:linespacing="125%"><tspan
       sodipodi:role="line"
       id="tspan2886-0-2"
       x="94.043755"
       y="127.70137">text07</tspan></text>
</g>

Private IP Detection

// description of your code here

Extending IPAddr:

require 'ipaddr'
class IPAddr
  PrivateRanges = [
    IPAddr.new("10.0.0.0/8"),
    IPAddr.new("172.16.0.0/12"),
    IPAddr.new("192.168.0.0/16")
  ]
  
  def private?
    return false unless self.ipv4?
    PrivateRanges.each do |ipr|
      return true if ipr.include?(self)
    end
    return false
  end

  def public?
    !private?
  end
end



TestCase:

require 'ipaddr'

class IpResolutionTest < Test::Unit::TestCase
  def ip(ipaddr)
    IPAddr.new(ipaddr)
  end
  
  def self.should_be_public_ip(ip)
    should "identify #{ip} as being public" do
      ip(ip).should be_public
    end
  end

  def self.should_be_private_ip(ip)
    should "identify #{ip} as being private" do
      ip(ip).should be_private
    end
  end
  
  context "Ip Resolution" do
    should_be_public_ip "9.255.255.255"
    should_be_public_ip "11.0.0.0"

    (0..5).each do |r1|
      (0..5).each do |r2| 
        should_be_private_ip "10.#{r1*50}.#{r2*50}.10"
      end
    end

    should_be_public_ip "172.15.255.255"
    should_be_public_ip "172.32.0.0"

    (16..31).each do |r1|
      (0..5).each do |r2| 
        should_be_private_ip "172.#{r1}.#{r2*50}.10"
      end
    end

    should_be_public_ip "192.167.255.255"
    should_be_public_ip "192.169.0.0"

    (0..5).each do |r1|
      (0..5).each do |r2| 
        should_be_private_ip "192.168.#{r1*50}.#{r2*50}"
      end
    end
  end
end






This is a subversion pre-commit hook

// This is a subversion pre-commit hook

#!/usr/bin/env ruby

repo_path = ARGV[0]
transaction = ARGV[1]
svnlook = '/usr/bin/svnlook'

commit_dirs_changed = `#{svnlook} dirs-changed #{repo_path} -t #{transaction}`
commit_changed = `#{svnlook} changed #{repo_path} -t #{transaction}`
#commit_author = `#{svnlook} author #{repo_path} -t #{transaction}`.chop
commit_log = `#{svnlook} log #{repo_path} -t #{transaction}`
#commit_diff = `#{svnlook} diff #{repo_path} -t #{transaction}`
#commit_date = `#{svnlook} date #{repo_path} -t #{transaction}`

# ******* Migration check ********
# if this is a migration then check that there is not already a migration with the same version number in the repository
files = commit_changed.split(/\n/)
current_migrations = nil
for file in files
  if(file =~ /A\s*(.*?\/migrate\/)(\d+)(.*)/)
    migration_path = $1
    migration_version = $2
    
    if(current_migrations == nil)
      current_migrations = {}
      migration_files = `#{svnlook} tree #{repo_path} #{migration_path}`
      for migration in migration_files
        current_migrations[$1] = true if(migration =~ /\s*(\d+)_(.*)/)
      end
    end
    
    if(current_migrations[migration_version])
     STDERR.puts("The is a pre-existing migration with version #{migration_version} in #{migration_path}")
     exit(1)
    end
  end
end



Extending acts_as_taggable for real-world

// description of your code here

module ActiveRecord
  module Acts #:nodoc:
    module Taggable #:nodoc:
      def self.included(base)
        base.extend(ClassMethods)  
      end
      
      module ClassMethods
        def acts_as_taggable(options = {})
          write_inheritable_attribute(:acts_as_taggable_options, {
            :taggable_type => ActiveRecord::Base.send(:class_name_of_active_record_descendant, self).to_s,
            :from => options[:from]
          })
          
          class_inheritable_reader :acts_as_taggable_options

          has_many :taggings, :as => :taggable, :dependent => true
          has_many :tags, :through => :taggings

          include ActiveRecord::Acts::Taggable::InstanceMethods
          extend ActiveRecord::Acts::Taggable::SingletonMethods          
        end
      end
      
      module SingletonMethods
        def find_tagged_with(list, options = {})
          local_options = { :limit => 1000, :offset => 0 }.merge(options)
          find_by_sql([
            "SELECT DISTINCT #{table_name}.* FROM #{table_name}, tags, taggings " +
            "WHERE #{table_name}.#{primary_key} = taggings.taggable_id " +
            "AND taggings.taggable_type = ? " +
            "AND taggings.tag_id = tags.id AND tags.name IN (?) #{"AND (#{local_options[:conditions]})" if local_options[:conditions]} LIMIT ? OFFSET ?",
            acts_as_taggable_options[:taggable_type], list, local_options[:limit], local_options[:offset]
          ])
        end
        
        def count_tagged_with(list, options = {})
          local_options = {}.merge(options)
          find_by_sql([
            "SELECT COUNT(DISTINCT #{table_name}.#{primary_key}) AS cnt FROM #{table_name}, tags, taggings " +
            "WHERE #{table_name}.#{primary_key} = taggings.taggable_id " +
            "AND taggings.taggable_type = ? " +
            "AND taggings.tag_id = tags.id AND tags.name IN (?) #{"AND (#{local_options[:conditions]}) " if local_options[:conditions]}",
            acts_as_taggable_options[:taggable_type], list
          ]).first.cnt.to_i
        end

        def find_tagged_with_intersecting(list, options = {})
          local_options = { :limit => 1000, :offset => 0 }.merge(options)
          find_by_sql([
            "SELECT DISTINCT #{table_name}.* FROM #{table_name}, tags, taggings " +
            "WHERE #{table_name}.#{primary_key} = taggings.taggable_id " +
            "AND taggings.taggable_type = ? " +
            "AND taggings.tag_id = tags.id AND tags.name IN (?) #{"AND (#{local_options[:conditions]}) " if local_options[:conditions]} GROUP BY #{table_name}.id HAVING COUNT(#{table_name}.id) = #{list.size} LIMIT ? OFFSET ?",
            acts_as_taggable_options[:taggable_type], list, local_options[:limit], local_options[:offset]
          ])
        end

        def count_tagged_with_intersecting(list, options = {})
          local_options = {}.merge(options)
          find_by_sql([
            "SELECT COUNT(*) AS cnt FROM (SELECT #{table_name}.#{primary_key} AS cnt FROM #{table_name}, tags, taggings " +
            "WHERE #{table_name}.#{primary_key} = taggings.taggable_id " +
            "AND taggings.taggable_type = ? " +
            "AND taggings.tag_id = tags.id AND tags.name IN (?) " +
            "#{"AND (#{local_options[:conditions]})" if local_options[:conditions]} " +
            "GROUP BY taggings.taggable_id HAVING COUNT(taggings.taggable_id) = #{list.size}) AS x",
            acts_as_taggable_options[:taggable_type], list
          ]).first.cnt.to_i
        end               
      end
      
      module InstanceMethods
        def tag_with(list)
          Tag.transaction do
            taggings.destroy_all

            Tag.parse(list).each do |name|
              if acts_as_taggable_options[:from]
                send(acts_as_taggable_options[:from]).tags.find_or_create_by_name(name).on(self)
              else
                Tag.find_or_create_by_name(name).on(self)
              end
            end
          end
        end

        def tag_list
          tags.collect { |tag| tag.name.include?(" ") ? "'#{tag.name}'" : tag.name }.join(" ")
        end
      end
    end
  end
end

Configure Subversion for Rails

// description of your code here

//desc "Configure Subversion for Rails"
task :configure_for_svn do
  system "svn remove log/*"
  system "svn commit -m 'removing all log files from subversion'"
  system 'svn propset svn:ignore "*.log" log/'
  system "svn update log/"
  system "svn commit -m 'Ignoring all files in /log/ ending in .log'"
  system 'svn propset svn:ignore "*.db" db/'
  system "svn update db/"
  system "svn commit -m 'Ignoring all files in /db/ ending in .db'"
  system "svn move config/database.yml config/database.example"
  system "svn commit -m 'Moving database.yml to database.example to provide a template for anyone who checks out the code'"
  system 'svn propset svn:ignore "database.yml" config/'
  system "svn update config/"
  system "svn commit -m 'Ignoring database.yml'"
  system "svn remove tmp/*"
  system "svn commit -m 'Removing /tmp/ folder'"
  system 'svn propset svn:ignore "*" tmp/'
end
   
desc "Add new files to subversion"
task :add_new_files do
   system "svn status | grep '^\?' | sed -e 's/? *//' | sed -e 's/ /\ /g' | xargs svn add"
end

desc "shortcut for adding new files"
task :add => [ :add_new_files ]

The acts_as_taggable plugin is great and so useful

// description of your code here

module ActiveRecord
  module Acts #:nodoc:
    module Taggable #:nodoc:
      def self.included(base)
        base.extend(ClassMethods)  
      end
      
      module ClassMethods
        def acts_as_taggable(options = {})
          write_inheritable_attribute(:acts_as_taggable_options, {
            :taggable_type => ActiveRecord::Base.send(:class_name_of_active_record_descendant, self).to_s,
            :from => options[:from]
          })
          
          class_inheritable_reader :acts_as_taggable_options

          has_many :taggings, :as => :taggable, :dependent => true
          has_many :tags, :through => :taggings

          include ActiveRecord::Acts::Taggable::InstanceMethods
          extend ActiveRecord::Acts::Taggable::SingletonMethods          
        end
      end
      
      module SingletonMethods
        def find_tagged_with(list)
          tagged_with list
        end

        def count_tagged_with(list)
          tagged_with list, :count
        end

        # DRY sql query and handle scope
        protected
        def tagged_with(list, type = :find)
          if type == :count
            sql = "SELECT COUNT(DISTINCT #{table_name}.#{primary_key}) AS cnt "
          else
            sql = "SELECT DISTINCT #{table_name}.* "
          end
          sql << "FROM #{table_name}, tags, taggings "

          conditions = [
            "#{table_name}.#{primary_key} = taggings.taggable_id " +
            "AND taggings.taggable_type = ? " +
            "AND taggings.tag_id = tags.id AND tags.name IN (?) ",
            acts_as_taggable_options[:taggable_type], list
            ]
          add_conditions!(sql, conditions)

          result = find_by_sql(sql)
          (type == :count) ? result.first.cnt.to_i : result
        end

      end
      
      module InstanceMethods
        def tag_with(list)
          Tag.transaction do
            taggings.destroy_all

            Tag.parse(list).each do |name|
              if acts_as_taggable_options[:from]
                send(acts_as_taggable_options[:from]).tags.find_or_create_by_name(name).on(self)
              else
                Tag.find_or_create_by_name(name).on(self)
              end
            end
          end
        end

        # allow using active record update_attributes() and others by using tag_list to set
        # and read the tag list
        alias tag_list= tag_with

        def tag_list
          tags.collect { |tag| tag.name.include?(" ") ? "'#{tag.name}'" : tag.name }.join(" ")
        end
      end
    end
  end
end

Filtering based on a has_and_belongs_to_many

// description of your code here

<h1>Listing tags</h1>

<table>
  <tr>
    <th>Name</th>
  </tr>

<% for tag in @tags %>
  <tr>
    <td><%=h tag.name %></td>
    <td><%= link_to 'Users', user_path(:tag_id=>tag) %></td>
    <td><%= link_to 'Show', tag_path(tag) %></td>
    <td><%= link_to 'Edit', edit_tag_path(tag) %></td>
    <td><%= link_to 'Destroy', tag_path(tag), :confirm => 'Are you sure?', :method => :delete %></td>
  </tr>
  <% end %>
</table>
<br />
<%= link_to 'New tag', new_tag_path %>