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-10 of 12 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

Java inflections

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Transforms words (from singular to plural, from camelCase to under_score, etc.). I got bored of doing Real Work...
 * 
 * @author chuyeow
 */
public class Inflector {

    // Pfft, can't think of a better name, but this is needed to avoid the price of initializing the pattern on each call.
    private static final Pattern UNDERSCORE_PATTERN_1 = Pattern.compile("([A-Z]+)([A-Z][a-z])");
    private static final Pattern UNDERSCORE_PATTERN_2 = Pattern.compile("([a-z\\d])([A-Z])");

    private static List<RuleAndReplacement> plurals = new ArrayList<RuleAndReplacement>();
    private static List<RuleAndReplacement> singulars = new ArrayList<RuleAndReplacement>();
    private static List<String> uncountables = new ArrayList<String>();

    private static Inflector instance; // (Pseudo-)Singleton instance.

    private Inflector() {
        // Woo, you can't touch me.
        
        initialize();
    }
    
    private void initialize() {
        plural("$", "s");
        plural("s$", "s");
        plural("(ax|test)is$", "$1es");
        plural("(octop|vir)us$", "$1i");
        plural("(alias|status)$", "$1es");
        plural("(bu)s$", "$1es");
        plural("(buffal|tomat)o$", "$1oes");
        plural("([ti])um$", "$1a");
        plural("sis$", "ses");
        plural("(?:([^f])fe|([lr])f)$", "$1$2ves");
        plural("(hive)$", "$1s");
        plural("([^aeiouy]|qu)y$", "$1ies");
        plural("([^aeiouy]|qu)ies$", "$1y");
        plural("(x|ch|ss|sh)$", "$1es");
        plural("(matr|vert|ind)ix|ex$", "$1ices");
        plural("([m|l])ouse$", "$1ice");
        plural("(ox)$", "$1en");
        plural("(quiz)$", "$1zes");

        singular("s$", "");
        singular("(n)ews$", "$1ews");
        singular("([ti])a$", "$1um");
        singular("((a)naly|(b)a|(d)iagno|(p)arenthe|(p)rogno|(s)ynop|(t)he)ses$", "$1$2sis");
        singular("(^analy)ses$", "$1sis");
        singular("([^f])ves$", "$1fe");
        singular("(hive)s$", "$1");
        singular("(tive)s$", "$1");
        singular("([lr])ves$", "$1f");
        singular("([^aeiouy]|qu)ies$", "$1y");
        singular("(s)eries$", "$1eries");
        singular("(m)ovies$", "$1ovie");
        singular("(x|ch|ss|sh)es$", "$1");
        singular("([m|l])ice$", "$1ouse");
        singular("(bus)es$", "$1");
        singular("(o)es$", "$1");
        singular("(shoe)s$", "$1");
        singular("(cris|ax|test)es$", "$1is");
        singular("([octop|vir])i$", "$1us");
        singular("(alias|status)es$", "$1");
        singular("^(ox)en", "$1");
        singular("(vert|ind)ices$", "$1ex");
        singular("(matr)ices$", "$1ix");
        singular("(quiz)zes$", "$1");

        irregular("person", "people");
        irregular("man", "men");
        irregular("child", "children");
        irregular("sex", "sexes");
        irregular("move", "moves");

        uncountable(new String[] {"equipment", "information", "rice", "money", "species", "series", "fish", "sheep"});
    }

    public static Inflector getInstance() {
        if (instance == null) {
            instance = new Inflector();
        }
        return instance;
    }

    public String underscore(String camelCasedWord) {

        // Regexes in Java are fucking stupid...
        String underscoredWord = UNDERSCORE_PATTERN_1.matcher(camelCasedWord).replaceAll("$1_$2");
        underscoredWord = UNDERSCORE_PATTERN_2.matcher(underscoredWord).replaceAll("$1_$2");
        underscoredWord = underscoredWord.replace('-', '_').toLowerCase();

        return underscoredWord;
    }

    public String pluralize(String word) {
        if (uncountables.contains(word.toLowerCase())) {
            return word;
        }
        return replaceWithFirstRule(word, plurals);
    }

    public String singularize(String word) {
        if (uncountables.contains(word.toLowerCase())) {
            return word;
        }
        return replaceWithFirstRule(word, singulars);
    }

    private String replaceWithFirstRule(String word, List<RuleAndReplacement> ruleAndReplacements) {

        for (RuleAndReplacement rar : ruleAndReplacements) {
            String rule = rar.getRule();
            String replacement = rar.getReplacement();

            // Return if we find a match.
            Matcher matcher = Pattern.compile(rule, Pattern.CASE_INSENSITIVE).matcher(word);
            if (matcher.find()) {
                return matcher.replaceAll(replacement);
            }
        }
        return word;
    }

    public String tableize(String className) {
        return pluralize(underscore(className));
    }
    
    public String tableize(Class klass) {
        // Strip away package name - we only want the 'base' class name.
        String className = klass.getName().replace(klass.getPackage().getName()+".", "");
        return tableize(className);
    }

    public static void plural(String rule, String replacement) {
        plurals.add(0, new RuleAndReplacement(rule, replacement));
    }

    public static void singular(String rule, String replacement) {
        singulars.add(0, new RuleAndReplacement(rule, replacement));
    }

    public static void irregular(String singular, String plural) {
        plural(singular, plural);
        singular(plural, singular);
    }

    public static void uncountable(String... words) {
        for (String word : words) {
            uncountables.add(word);
        }
    }
}


// Ugh, no open structs in Java (not-natively at least).
class RuleAndReplacement {
    private String rule;
    private String replacement;
    public RuleAndReplacement(String rule, String replacement) {
        this.rule = rule;
        this.replacement = replacement;
    }
    public String getReplacement() {
        return replacement;
    }
    public void setReplacement(String replacement) {
        this.replacement = replacement;
    }
    public String getRule() {
        return rule;
    }
    public void setRule(String rule) {
        this.rule = rule;
    }
}

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

Making applications installed from source uninstallable



# Install checkinstall and auto-apt if they aren't already installed.
sudo apt-get install checkinstall auto-apt


auto-apt run ./configure
make
sudo checkinstall # instead of "make install"
« Newer Snippets
Older Snippets »
Showing 1-10 of 12 total  RSS