Blogged by Ujihisa. Standard methods of programming and thoughts including Clojure, Vim, LLVM, Haskell, Ruby and Mathematics written by a Japanese programmer. github/ujihisa

Saturday, April 25, 2009

Refactored kmdsbng's opt_simple

http://github.com/ujihisa/opt_simple/tree/master

The patch summary here:

$ git diff dabfeb66321e01ed59a8127ffe545ff01ae8ca4d..HEAD -- lib

diff --git a/lib/opt_simple.rb b/lib/opt_simple.rb
index 1810d3d..b917afb 100644
--- a/lib/opt_simple.rb
+++ b/lib/opt_simple.rb
@@ -5,36 +5,27 @@ class OptSimple

   def initialize(spec, argv)
     parser = OptionParser.new
-    spec.each{|s|
-      main_option_name = option_names = nil
-      if (!(s.kind_of? Array))
-        s = [s]
-      end
+    spec.each do |s|
+      s = [s] unless s.kind_of? Array

-      option_names = s[0..1].select{|o| o =~ /^-/}.map{|o| o.split[0].gsub(/^(\-)+/, '').gsub(/-/, '_')}
-      main_option_name = option_names.shift
+      main_option_name, *option_names = s[0..1].select {|o| /^-/ =~ o }.
+        map {|o| o.split[0].gsub(/^(\-)+/, '').gsub('-', '_') }

-      # regist parser
-      parser.on(*s){|v|
+      # register parser
+      parser.on(*s) {|v|
         instance_variable_set('@' + main_option_name, v)
       }

       # define getter
-      self.class.class_eval {
-        define_method(main_option_name) {
-          instance_variable_get('@' + main_option_name)
-        }
-      }
+      self.class.__send__(
+        :attr_reader, main_option_name.to_sym)

       # define getter alias
-      option_names.each{|s|
-        self.class.class_eval {
-          alias_method s, main_option_name
-        }
-      }
-    }
+      option_names.each do |s|
+        self.class.__send__(
+          :alias_method, s, main_option_name)
+      end
+    end
     @remain = parser.parse(argv)
   end
 end
-
-

KansaiRubyWorkshop++

No comments:

Post a Comment

Followers