RubyとWSHでユーザー環境変数を設定する

チクタク…チクタク…

# coding: CP932

module OLE
  require "win32ole"
  
  module Environment

    MEMBERS = {
      HTTP_PROXY: [
        [ :protocol, :username, :password, :host, :port ],
        %r{^(.*?)//(.*?):(.*?)@(.*?):(.*?)$},
        lambda{ |values| "%s//%s:%s@%s:%s"%values },
      ],
    }

    module User

      class << self

        def [](name)
          wsh = WIN32OLE.new("WScript.Shell")
          obj = wsh.Environment(self.name.split(/::/).last.capitalize)
          variable(obj, name)
        end

        def variable(obj, name)

          attrs, pattern, format = *MEMBERS[name.to_sym]

          Struct.new(name, *attrs) do
            define_method( :name )   { name }
            define_method( :value )  { values.join.empty? ? nil : format[values] }
            define_method( :show )   { puts value }
            define_method( :load )   { members.zip( obj[name].scan(pattern).flatten ).each{ |m, v| self[m] = v } ; self }
            define_method( :save )   { value ? obj[name] = value : remove ; self }
            define_method( :remove ) { load && obj.Remove(name) }
          end

        end

      end

    end
    
  end

end

http_proxy = OLE::Environment::User["HTTP_PROXY"].new
http_proxy.load.show                              # =>
http_proxy.protocol = "http:"
http_proxy.username = "username"
http_proxy.password = "password"
http_proxy.host     = "proxy.host.ne.jp"
http_proxy.port     = "8080"
http_proxy.show                                   # =>http://username:password@proxy.host.ne.jp:8080
http_proxy.save
http_proxy.load.show                              # =>http://username:password@proxy.host.ne.jp:8080
http_proxy.password = http_proxy.password.reverse
http_proxy.port     = http_proxy.port[0,3] << "8"
http_proxy.show                                   # =>http://username:drowssap@proxy.host.ne.jp:8088
http_proxy.save
http_proxy.load.show                              # =>http://username:drowssap@proxy.host.ne.jp:8088