<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DZone Snippets: Chuyeow's Code Snippets</title>
    <link>http://snippets.dzone.com/posts</link>
    <pubDate>Sat, 17 May 2008 02:36:05 GMT</pubDate>
    <description>DZone Snippets: Chuyeow's Code Snippets</description>
    <item>
      <title>Removing empty directories (non-recursive)</title>
      <link>http://snippets.dzone.com/posts/show/4564</link>
      <description>// Simple class to remove empty directories.&lt;br /&gt;&lt;br /&gt;&lt;code&gt;&lt;br /&gt;require 'fileutils'&lt;br /&gt;&lt;br /&gt;class ReorgBot&lt;br /&gt;&lt;br /&gt;  attr_accessor :path&lt;br /&gt;  attr_accessor :dir&lt;br /&gt;&lt;br /&gt;  def initialize(path)&lt;br /&gt;    raise ArgumentError, "path '#{path}' does not exist!" unless File.exist?(path)&lt;br /&gt;    raise ArgumentError, "path '#{path} is not a directory you dolt!" unless File.directory?(path)&lt;br /&gt;    @path = path&lt;br /&gt;    @dir = Dir.new(path)&lt;br /&gt;  end&lt;br /&gt;&lt;br /&gt;  def dirs&lt;br /&gt;    @dir.select { |f| File.directory?(File.join(@path, f)) }&lt;br /&gt;  end&lt;br /&gt;&lt;br /&gt;  def empty_dirs&lt;br /&gt;    dirs.select { |d| Dir[File.join(@path, d, '*')].empty? }&lt;br /&gt;  end&lt;br /&gt;&lt;br /&gt;  def non_empty_dirs&lt;br /&gt;    dirs - empty_dirs&lt;br /&gt;  end&lt;br /&gt;&lt;br /&gt;  def remove_empty_dirs&lt;br /&gt;    empty_dirs.each do |d|&lt;br /&gt;      FileUtils.rm_rf(File.join(@path, d))&lt;br /&gt;    end&lt;br /&gt;  end&lt;br /&gt;end&lt;br /&gt;&lt;br /&gt;bot = ReorgBot.new('/tmp/reorg_test')&lt;br /&gt;bot.remove_empty_dirs&lt;br /&gt;&lt;/code&gt;</description>
      <pubDate>Fri, 21 Sep 2007 03:49:21 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/4564</guid>
      <author>chuyeow (Chu Yeow)</author>
    </item>
    <item>
      <title>Java inflections</title>
      <link>http://snippets.dzone.com/posts/show/4110</link>
      <description>&lt;code&gt;&lt;br /&gt;import java.util.ArrayList;&lt;br /&gt;import java.util.List;&lt;br /&gt;import java.util.regex.Matcher;&lt;br /&gt;import java.util.regex.Pattern;&lt;br /&gt;&lt;br /&gt;/**&lt;br /&gt; * Transforms words (from singular to plural, from camelCase to under_score, etc.). I got bored of doing Real Work...&lt;br /&gt; * &lt;br /&gt; * @author chuyeow&lt;br /&gt; */&lt;br /&gt;public class Inflector {&lt;br /&gt;&lt;br /&gt;    // Pfft, can't think of a better name, but this is needed to avoid the price of initializing the pattern on each call.&lt;br /&gt;    private static final Pattern UNDERSCORE_PATTERN_1 = Pattern.compile("([A-Z]+)([A-Z][a-z])");&lt;br /&gt;    private static final Pattern UNDERSCORE_PATTERN_2 = Pattern.compile("([a-z\\d])([A-Z])");&lt;br /&gt;&lt;br /&gt;    private static List&lt;RuleAndReplacement&gt; plurals = new ArrayList&lt;RuleAndReplacement&gt;();&lt;br /&gt;    private static List&lt;RuleAndReplacement&gt; singulars = new ArrayList&lt;RuleAndReplacement&gt;();&lt;br /&gt;    private static List&lt;String&gt; uncountables = new ArrayList&lt;String&gt;();&lt;br /&gt;&lt;br /&gt;    private static Inflector instance; // (Pseudo-)Singleton instance.&lt;br /&gt;&lt;br /&gt;    private Inflector() {&lt;br /&gt;        // Woo, you can't touch me.&lt;br /&gt;        &lt;br /&gt;        initialize();&lt;br /&gt;    }&lt;br /&gt;    &lt;br /&gt;    private void initialize() {&lt;br /&gt;        plural("$", "s");&lt;br /&gt;        plural("s$", "s");&lt;br /&gt;        plural("(ax|test)is$", "$1es");&lt;br /&gt;        plural("(octop|vir)us$", "$1i");&lt;br /&gt;        plural("(alias|status)$", "$1es");&lt;br /&gt;        plural("(bu)s$", "$1es");&lt;br /&gt;        plural("(buffal|tomat)o$", "$1oes");&lt;br /&gt;        plural("([ti])um$", "$1a");&lt;br /&gt;        plural("sis$", "ses");&lt;br /&gt;        plural("(?:([^f])fe|([lr])f)$", "$1$2ves");&lt;br /&gt;        plural("(hive)$", "$1s");&lt;br /&gt;        plural("([^aeiouy]|qu)y$", "$1ies");&lt;br /&gt;        plural("([^aeiouy]|qu)ies$", "$1y");&lt;br /&gt;        plural("(x|ch|ss|sh)$", "$1es");&lt;br /&gt;        plural("(matr|vert|ind)ix|ex$", "$1ices");&lt;br /&gt;        plural("([m|l])ouse$", "$1ice");&lt;br /&gt;        plural("(ox)$", "$1en");&lt;br /&gt;        plural("(quiz)$", "$1zes");&lt;br /&gt;&lt;br /&gt;        singular("s$", "");&lt;br /&gt;        singular("(n)ews$", "$1ews");&lt;br /&gt;        singular("([ti])a$", "$1um");&lt;br /&gt;        singular("((a)naly|(b)a|(d)iagno|(p)arenthe|(p)rogno|(s)ynop|(t)he)ses$", "$1$2sis");&lt;br /&gt;        singular("(^analy)ses$", "$1sis");&lt;br /&gt;        singular("([^f])ves$", "$1fe");&lt;br /&gt;        singular("(hive)s$", "$1");&lt;br /&gt;        singular("(tive)s$", "$1");&lt;br /&gt;        singular("([lr])ves$", "$1f");&lt;br /&gt;        singular("([^aeiouy]|qu)ies$", "$1y");&lt;br /&gt;        singular("(s)eries$", "$1eries");&lt;br /&gt;        singular("(m)ovies$", "$1ovie");&lt;br /&gt;        singular("(x|ch|ss|sh)es$", "$1");&lt;br /&gt;        singular("([m|l])ice$", "$1ouse");&lt;br /&gt;        singular("(bus)es$", "$1");&lt;br /&gt;        singular("(o)es$", "$1");&lt;br /&gt;        singular("(shoe)s$", "$1");&lt;br /&gt;        singular("(cris|ax|test)es$", "$1is");&lt;br /&gt;        singular("([octop|vir])i$", "$1us");&lt;br /&gt;        singular("(alias|status)es$", "$1");&lt;br /&gt;        singular("^(ox)en", "$1");&lt;br /&gt;        singular("(vert|ind)ices$", "$1ex");&lt;br /&gt;        singular("(matr)ices$", "$1ix");&lt;br /&gt;        singular("(quiz)zes$", "$1");&lt;br /&gt;&lt;br /&gt;        irregular("person", "people");&lt;br /&gt;        irregular("man", "men");&lt;br /&gt;        irregular("child", "children");&lt;br /&gt;        irregular("sex", "sexes");&lt;br /&gt;        irregular("move", "moves");&lt;br /&gt;&lt;br /&gt;        uncountable(new String[] {"equipment", "information", "rice", "money", "species", "series", "fish", "sheep"});&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    public static Inflector getInstance() {&lt;br /&gt;        if (instance == null) {&lt;br /&gt;            instance = new Inflector();&lt;br /&gt;        }&lt;br /&gt;        return instance;&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    public String underscore(String camelCasedWord) {&lt;br /&gt;&lt;br /&gt;        // Regexes in Java are fucking stupid...&lt;br /&gt;        String underscoredWord = UNDERSCORE_PATTERN_1.matcher(camelCasedWord).replaceAll("$1_$2");&lt;br /&gt;        underscoredWord = UNDERSCORE_PATTERN_2.matcher(underscoredWord).replaceAll("$1_$2");&lt;br /&gt;        underscoredWord = underscoredWord.replace('-', '_').toLowerCase();&lt;br /&gt;&lt;br /&gt;        return underscoredWord;&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    public String pluralize(String word) {&lt;br /&gt;        if (uncountables.contains(word.toLowerCase())) {&lt;br /&gt;            return word;&lt;br /&gt;        }&lt;br /&gt;        return replaceWithFirstRule(word, plurals);&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    public String singularize(String word) {&lt;br /&gt;        if (uncountables.contains(word.toLowerCase())) {&lt;br /&gt;            return word;&lt;br /&gt;        }&lt;br /&gt;        return replaceWithFirstRule(word, singulars);&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    private String replaceWithFirstRule(String word, List&lt;RuleAndReplacement&gt; ruleAndReplacements) {&lt;br /&gt;&lt;br /&gt;        for (RuleAndReplacement rar : ruleAndReplacements) {&lt;br /&gt;            String rule = rar.getRule();&lt;br /&gt;            String replacement = rar.getReplacement();&lt;br /&gt;&lt;br /&gt;            // Return if we find a match.&lt;br /&gt;            Matcher matcher = Pattern.compile(rule, Pattern.CASE_INSENSITIVE).matcher(word);&lt;br /&gt;            if (matcher.find()) {&lt;br /&gt;                return matcher.replaceAll(replacement);&lt;br /&gt;            }&lt;br /&gt;        }&lt;br /&gt;        return word;&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    public String tableize(String className) {&lt;br /&gt;        return pluralize(underscore(className));&lt;br /&gt;    }&lt;br /&gt;    &lt;br /&gt;    public String tableize(Class klass) {&lt;br /&gt;        // Strip away package name - we only want the 'base' class name.&lt;br /&gt;        String className = klass.getName().replace(klass.getPackage().getName()+".", "");&lt;br /&gt;        return tableize(className);&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    public static void plural(String rule, String replacement) {&lt;br /&gt;        plurals.add(0, new RuleAndReplacement(rule, replacement));&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    public static void singular(String rule, String replacement) {&lt;br /&gt;        singulars.add(0, new RuleAndReplacement(rule, replacement));&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    public static void irregular(String singular, String plural) {&lt;br /&gt;        plural(singular, plural);&lt;br /&gt;        singular(plural, singular);&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    public static void uncountable(String... words) {&lt;br /&gt;        for (String word : words) {&lt;br /&gt;            uncountables.add(word);&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;// Ugh, no open structs in Java (not-natively at least).&lt;br /&gt;class RuleAndReplacement {&lt;br /&gt;    private String rule;&lt;br /&gt;    private String replacement;&lt;br /&gt;    public RuleAndReplacement(String rule, String replacement) {&lt;br /&gt;        this.rule = rule;&lt;br /&gt;        this.replacement = replacement;&lt;br /&gt;    }&lt;br /&gt;    public String getReplacement() {&lt;br /&gt;        return replacement;&lt;br /&gt;    }&lt;br /&gt;    public void setReplacement(String replacement) {&lt;br /&gt;        this.replacement = replacement;&lt;br /&gt;    }&lt;br /&gt;    public String getRule() {&lt;br /&gt;        return rule;&lt;br /&gt;    }&lt;br /&gt;    public void setRule(String rule) {&lt;br /&gt;        this.rule = rule;&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;/code&gt;</description>
      <pubDate>Thu, 07 Jun 2007 06:24:16 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/4110</guid>
      <author>chuyeow (Chu Yeow)</author>
    </item>
    <item>
      <title>Helper for displaying flash</title>
      <link>http://snippets.dzone.com/posts/show/3978</link>
      <description>&lt;code&gt;&lt;br /&gt;// Add this to your application_helper.rb.&lt;br /&gt;&lt;br /&gt;  def display_standard_flashes&lt;br /&gt;    known_levels = [:error, :warning, :notice] # highest priority to lowest&lt;br /&gt;    level = known_levels.find { |level| flash.has_key?(level) }&lt;br /&gt;    level ? content_tag('div', flash[level], :class =&gt; "flash #{level}") : nil&lt;br /&gt;  end&lt;br /&gt;&lt;/code&gt;</description>
      <pubDate>Thu, 10 May 2007 06:21:42 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/3978</guid>
      <author>chuyeow (Chu Yeow)</author>
    </item>
    <item>
      <title>WEBrick servlet with HTTP authentication</title>
      <link>http://snippets.dzone.com/posts/show/3830</link>
      <description>// HTTP authentication for a directory listing&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;code&gt;&lt;br /&gt;require 'webrick'&lt;br /&gt;include WEBrick&lt;br /&gt;&lt;br /&gt;dir = Dir::pwd&lt;br /&gt;port = 1234&lt;br /&gt;&lt;br /&gt;authenticate = Proc.new do |req, res|&lt;br /&gt;  HTTPAuth.basic_auth(req, res, '') do |user, password|&lt;br /&gt;    user == 'foo' &amp;&amp; password == 'bar'&lt;br /&gt;  end&lt;br /&gt;end&lt;br /&gt;&lt;br /&gt;s = HTTPServer.new(:Port =&gt; port, :ServerType =&gt; Daemon)&lt;br /&gt;s.mount('/', HTTPServlet::FileHandler, dir,&lt;br /&gt;  :FancyIndexing =&gt; true,&lt;br /&gt;  :HandlerCallback =&gt; authenticate # Hook up the authentication proc.&lt;br /&gt;)&lt;br /&gt;&lt;br /&gt;trap('INT') { s.shutdown }&lt;br /&gt;s.start&lt;br /&gt;&lt;/code&gt;</description>
      <pubDate>Mon, 16 Apr 2007 15:12:46 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/3830</guid>
      <author>chuyeow (Chu Yeow)</author>
    </item>
    <item>
      <title>WEBrick servlet skeleton</title>
      <link>http://snippets.dzone.com/posts/show/3829</link>
      <description>// Skeleton code for a WEBrick servlet.&lt;br /&gt;&lt;br /&gt;&lt;code&gt;&lt;br /&gt;require 'webrick'&lt;br /&gt;include WEBrick&lt;br /&gt;class UberServlet &lt; HTTPServlet::AbstractServlet&lt;br /&gt;&lt;br /&gt;  def do_GET(req, res)&lt;br /&gt;    id = req.query['id'] # Get GET/POST params like that.&lt;br /&gt;    res['content-type'] = 'text/html'&lt;br /&gt;    res.status = 200&lt;br /&gt;    res.body = some_text&lt;br /&gt;  end&lt;br /&gt;  alias :do_POST :do_GET&lt;br /&gt;&lt;br /&gt;end&lt;br /&gt;&lt;br /&gt;# "Mount" the servlet.&lt;br /&gt;server = HTTPServer.new(:Port =&gt; 1234)&lt;br /&gt;server.mount('/some/path', UberServlet)&lt;br /&gt;&lt;br /&gt;# Handle signals.&lt;br /&gt;%w(INT TERM).each do |signal|&lt;br /&gt;  trap(signal) { server.shutdown }&lt;br /&gt;end&lt;br /&gt;&lt;br /&gt;server.start&lt;br /&gt;&lt;/code&gt;</description>
      <pubDate>Mon, 16 Apr 2007 15:08:46 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/3829</guid>
      <author>chuyeow (Chu Yeow)</author>
    </item>
    <item>
      <title>Struct "magic" - creating objects from CSV file</title>
      <link>http://snippets.dzone.com/posts/show/3828</link>
      <description>&lt;br /&gt;&lt;code&gt;&lt;br /&gt;require 'csv'&lt;br /&gt;&lt;br /&gt;csv = CSV.open('some_file.csv', 'r')&lt;br /&gt;Post = Struct.new(*(csv.shift.map { |f| f.to_sym })) # Nice! Read in CSV header, turns them into symbols, and creates a new Struct.&lt;br /&gt;posts = csv.inject([]) do |posts, row|&lt;br /&gt;  posts &lt;&lt; Post[*row]&lt;br /&gt;end&lt;br /&gt;csv.close&lt;br /&gt;&lt;/code&gt;</description>
      <pubDate>Mon, 16 Apr 2007 15:04:15 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/3828</guid>
      <author>chuyeow (Chu Yeow)</author>
    </item>
    <item>
      <title>Ruby Struct example</title>
      <link>http://snippets.dzone.com/posts/show/3827</link>
      <description>&lt;br /&gt;&lt;code&gt;&lt;br /&gt;Post = Struct.new(:id, :title, :content, :created_at)&lt;br /&gt;&lt;br /&gt;# Some database access, maybe via DBI.&lt;br /&gt;while row = @stmt.fetch do&lt;br /&gt;  posts &lt;&lt; Post.new(*row)&lt;br /&gt;end&lt;br /&gt;&lt;/code&gt;</description>
      <pubDate>Mon, 16 Apr 2007 15:00:12 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/3827</guid>
      <author>chuyeow (Chu Yeow)</author>
    </item>
    <item>
      <title>Add a to_conditions method to ActiveRecord::Base for converting models to finder :conditions hash.</title>
      <link>http://snippets.dzone.com/posts/show/3732</link>
      <description>// Mixes in a to_conditions method to ActiveRecord::Base. Converts the attributes of an AR object to a&lt;br /&gt;// ActiveRecord::Base#find :conditions hash. Useful for comparing AR objects, especially when looking for&lt;br /&gt;// duplicates.&lt;br /&gt;// E.g.&lt;br /&gt;//   &lt;br /&gt;//   if not Post.find(:all, :conditions =&gt; my_post.conditions).empty?&lt;br /&gt;//     puts "Duplicate found"&lt;br /&gt;//   end&lt;br /&gt;&lt;br /&gt;&lt;code&gt;&lt;br /&gt;module Bezurk #:nodoc:&lt;br /&gt;  module ActiveRecord #:nodoc:&lt;br /&gt;    module Extensions&lt;br /&gt;      def to_conditions&lt;br /&gt;        attributes.inject({}) do |hash, (name, value)|&lt;br /&gt;          hash.merge(name.intern =&gt; value)&lt;br /&gt;        end&lt;br /&gt;      end&lt;br /&gt;      alias :to_conditions_hash :to_conditions&lt;br /&gt;    end&lt;br /&gt;  end&lt;br /&gt;end&lt;br /&gt;&lt;br /&gt;ActiveRecord::Base.send(:include, Bezurk::ActiveRecord::Extensions)&lt;br /&gt;&lt;/code&gt;</description>
      <pubDate>Mon, 26 Mar 2007 10:54:25 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/3732</guid>
      <author>chuyeow (Chu Yeow)</author>
    </item>
    <item>
      <title>Updating Rubygems and gems</title>
      <link>http://snippets.dzone.com/posts/show/3550</link>
      <description>// Update Rubygems to the latest version, and getting the latest gems, and then cleaning up.&lt;br /&gt;&lt;br /&gt;&lt;code&gt;&lt;br /&gt;sudo gem update --system  # Update to latest Rubygems (if any)&lt;br /&gt;gem outdated  # Get list of outdated gems and update as necessary&lt;br /&gt;sudo gem install XXX --include-dependencies&lt;br /&gt;sudo gem clean  # Clean up outdated gems&lt;br /&gt;&lt;/code&gt;</description>
      <pubDate>Tue, 20 Feb 2007 09:14:13 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/3550</guid>
      <author>chuyeow (Chu Yeow)</author>
    </item>
    <item>
      <title>Making applications installed from source uninstallable</title>
      <link>http://snippets.dzone.com/posts/show/3410</link>
      <description>&lt;br /&gt;&lt;br /&gt;&lt;code&gt;&lt;br /&gt;# Install checkinstall and auto-apt if they aren't already installed.&lt;br /&gt;sudo apt-get install checkinstall auto-apt&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;auto-apt run ./configure&lt;br /&gt;make&lt;br /&gt;sudo checkinstall # instead of "make install"&lt;br /&gt;&lt;/code&gt;</description>
      <pubDate>Sun, 04 Feb 2007 16:24:29 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/3410</guid>
      <author>chuyeow (Chu Yeow)</author>
    </item>
  </channel>
</rss>
