Hatena::ブログ(Diary)

わからん

2010.12.11

[] ObjectSpace.each_object の Nick Sieger さんの利用例

Ruby’s Exception Hierarchy で公開されている、例外の階層構造を出力するプログラムで ObjectSpace.each_object(Class) をみつけました。こういうときに使えるのか。短いのでまるごと引用。出力は元記事を参照して下さい。pp tree したり tap が確認に役立ちます。 あと、delete_if {|e| [Object, Kernel].include? e } のところがかわいいなと思いました。

exceptions = []
tree = {}
ObjectSpace.each_object(Class) do |cls|        #すべてのクラスに対して以下をチェック
  next unless cls.ancestors.include? Exception
  next if exceptions.include? cls
  next if cls.superclass == SystemCallError # avoid dumping Errno's
  exceptions << cls
  cls.ancestors.delete_if {|e| [Object, Kernel].include? e }.reverse.inject(tree) {|memo,cls| memo[cls] ||= {}}
end

indent = 0
tree_printer = Proc.new do |t|
  t.keys.sort { |c1,c2| c1.name <=> c2.name }.each do |k|
    space = (' ' * indent); space ||= ''
    puts space + k.to_s
    indent += 2; tree_printer.call t[k]; indent -= 2
  end
end
tree_printer.call tree

[] emacs 内でログファイルを tail -f する設定

日本タイルで有名な matsuu さんのブログ記事で、M-x auto-revert-tail-mode を知りました*1。emacs 内で ログファイルをチェックできれば、anything-c-moccer などの強力な検索機能が使えて便利です。そこで、この auto-revert-tail-mode という関数/マイナーモードをより使いやすくする設定を書きました。以下の3つの機能を提供します。

  1. /var/log/ 以下のファイルは自動的に auto-revert-tail-mode マイナーモードで開く
  2. バッファ更新時は最新のログを表示するように、ポイントをバッファの末尾に移動させる
  3. 指定したキーワードを目立たせる

dot.emacs に次の設定を追記します。

(defun my-auto-revert-tail-mode-on ()
  (interactive)
  (when (string-match "^/var/log/" default-directory)
          (auto-revert-tail-mode t)))

(add-hook 'find-file-hook 'my-auto-revert-tail-mode-on)

(add-hook 'after-revert-hook
          (lambda ()
            (when auto-revert-tail-mode
              (end-of-buffer))))

特定のキーワードをハイライト表示するには、次のコードを追記し、M-x my-keep-highlight-regexp すれば、対象とする語を指定できます。

;;http://d.hatena.ne.jp/kitokitoki/20100706/p1
(make-face 'my-highlight-face)
(set-face-foreground 'my-highlight-face "black")
(set-face-background 'my-highlight-face "yellow")
(setq my-highlight-face 'my-highlight-face)

(defun my-keep-highlight-regexp (re)
  (interactive "sRegexp: \n")
  (setq my-highlight-keyword re)
  (my-keep-highlight-set-font-lock my-highlight-keyword))

(defun my-keep-highlight-symbole-at-point ()
  (interactive)
  (setq my-highlight-keyword (or (thing-at-point 'symbol) ""))
  (my-keep-highlight-set-font-lock my-highlight-keyword))

(defun my-keep-highlight-set-font-lock (re)
  (font-lock-add-keywords 'nil (list (list re 0 my-highlight-face t)))
  (font-lock-fontify-buffer))
 
(defun my-cancel-highlight-regexp ()
  (interactive)
  (font-lock-remove-keywords 'nil (list (list my-highlight-keyword 0 my-highlight-face t)))
  (font-lock-fontify-buffer))

;; (defalias 'h 'my-keep-highlight-regexp) ;エイリアスサンプル

*1:auto-revert-tail-mode は、tail.el や symfony.el、rails.el でも利用されていません。

Google