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

About this user

Chu Yeow http://blog.codefront.net/

« Newer Snippets
Older Snippets »
Showing 1-9 of 9 total  RSS 

Removing empty directories (non-recursive)

// Simple class to remove empty directories.

require 'fileutils'

class ReorgBot

  attr_accessor :path
  attr_accessor :dir

  def initialize(path)
    raise ArgumentError, "path '#{path}' does not exist!" unless File.exist?(path)
    raise ArgumentError, "path '#{path} is not a directory you dolt!" unless File.directory?(path)
    @path = path
    @dir = Dir.new(path)
  end

  def dirs
    @dir.select { |f| File.directory?(File.join(@path, f)) }
  end

  def empty_dirs
    dirs.select { |d| Dir[File.join(@path, d, '*')].empty? }
  end

  def non_empty_dirs
    dirs - empty_dirs
  end

  def remove_empty_dirs
    empty_dirs.each do |d|
      FileUtils.rm_rf(File.join(@path, d))
    end
  end
end

bot = ReorgBot.new('/tmp/reorg_test')
bot.remove_empty_dirs

Helper for displaying flash

// Add this to your application_helper.rb.

  def display_standard_flashes
    known_levels = [:error, :warning, :notice] # highest priority to lowest
    level = known_levels.find { |level| flash.has_key?(level) }
    level ? content_tag('div', flash[level], :class => "flash #{level}") : nil
  end

WEBrick servlet with HTTP authentication

// HTTP authentication for a directory listing


require 'webrick'
include WEBrick

dir = Dir::pwd
port = 1234

authenticate = Proc.new do |req, res|
  HTTPAuth.basic_auth(req, res, '') do |user, password|
    user == 'foo' && password == 'bar'
  end
end

s = HTTPServer.new(:Port => port, :ServerType => Daemon)
s.mount('/', HTTPServlet::FileHandler, dir,
  :FancyIndexing => true,
  :HandlerCallback => authenticate # Hook up the authentication proc.
)

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

WEBrick servlet skeleton

// Skeleton code for a WEBrick servlet.

require 'webrick'
include WEBrick
class UberServlet < HTTPServlet::AbstractServlet

  def do_GET(req, res)
    id = req.query['id'] # Get GET/POST params like that.
    res['content-type'] = 'text/html'
    res.status = 200
    res.body = some_text
  end
  alias :do_POST :do_GET

end

# "Mount" the servlet.
server = HTTPServer.new(:Port => 1234)
server.mount('/some/path', UberServlet)

# Handle signals.
%w(INT TERM).each do |signal|
  trap(signal) { server.shutdown }
end

server.start

Struct "magic" - creating objects from CSV file


require 'csv'

csv = CSV.open('some_file.csv', 'r')
Post = Struct.new(*(csv.shift.map { |f| f.to_sym })) # Nice! Read in CSV header, turns them into symbols, and creates a new Struct.
posts = csv.inject([]) do |posts, row|
  posts << Post[*row]
end
csv.close

Ruby Struct example


Post = Struct.new(:id, :title, :content, :created_at)

# Some database access, maybe via DBI.
while row = @stmt.fetch do
  posts << Post.new(*row)
end

Add a to_conditions method to ActiveRecord::Base for converting models to finder :conditions hash.

// Mixes in a to_conditions method to ActiveRecord::Base. Converts the attributes of an AR object to a
// ActiveRecord::Base#find :conditions hash. Useful for comparing AR objects, especially when looking for
// duplicates.
// E.g.
//
// if not Post.find(:all, :conditions => my_post.conditions).empty?
// puts "Duplicate found"
// end

module Bezurk #:nodoc:
  module ActiveRecord #:nodoc:
    module Extensions
      def to_conditions
        attributes.inject({}) do |hash, (name, value)|
          hash.merge(name.intern => value)
        end
      end
      alias :to_conditions_hash :to_conditions
    end
  end
end

ActiveRecord::Base.send(:include, Bezurk::ActiveRecord::Extensions)

Updating Rubygems and gems

// Update Rubygems to the latest version, and getting the latest gems, and then cleaning up.

sudo gem update --system  # Update to latest Rubygems (if any)
gem outdated  # Get list of outdated gems and update as necessary
sudo gem install XXX --include-dependencies
sudo gem clean  # Clean up outdated gems

Running a single test method with ZenTest

// HOWTO run a single test method.
// You need ZenTest installed (gem install ZenTest).

# Run ruby_fork in the background.
ruby_fork -rubygems -e 'require_gem "rails"' &

# Run a single test method.
ruby_fork_client -r test/functional/account_controller_test.rb -- -n test_unactivated_user_should_activate
« Newer Snippets
Older Snippets »
Showing 1-9 of 9 total  RSS