/ emacs.d / rails / rails-project.el
rails-project.el
 1  ;;; rails-project.el ---
 2  
 3  ;; Copyright (C) 2006 Dmitry Galinsky <dima dot exe at gmail dot com>
 4  
 5  ;; Authors: Dmitry Galinsky <dima dot exe at gmail dot com>,
 6  
 7  ;; Keywords: ruby rails languages oop
 8  ;; $URL: svn+ssh://rubyforge/var/svn/emacs-rails/trunk/rails.el $
 9  ;; $Id: rails.el 149 2007-03-29 15:07:49Z dimaexe $
10  
11  ;;; License
12  
13  ;; This program is free software; you can redistribute it and/or
14  ;; modify it under the terms of the GNU General Public License
15  ;; as published by the Free Software Foundation; either version 2
16  ;; of the License, or (at your option) any later version.
17  
18  ;; This program is distributed in the hope that it will be useful,
19  ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20  ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
21  ;; GNU General Public License for more details.
22  
23  ;; You should have received a copy of the GNU General Public License
24  ;; along with this program; if not, write to the Free Software
25  ;; Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
26  
27  ;;; Code:
28  
29  (defun rails-project:root ()
30    "Return RAILS_ROOT if this file is a part of a Rails application,
31  else return nil"
32    (let ((curdir default-directory)
33          (max 10)
34          (found nil))
35      (while (and (not found) (> max 0))
36        (progn
37          (if (file-exists-p (concat curdir "config/environment.rb"))
38              (progn
39                (setq found t))
40            (progn
41              (setq curdir (concat curdir "../"))
42              (setq max (- max 1))))))
43      (if found (expand-file-name curdir))))
44  
45  (defmacro* rails-project:with-root ((root) &body body)
46    "If you use `rails-project:root' or functions related on it
47  several times in a block of code, you can optimize your code by
48  using this macro. Also, blocks of code will be executed only if
49  rails-root exist.
50   (rails-project:with-root (root)
51      (foo root)
52      (bar (rails-core:file \"some/path\")))
53   "
54   `(let ((,root (rails-project:root)))
55      (when ,root
56        (flet ((rails-project:root () ,root))
57          ,@body))))
58  
59  (defmacro rails-project:in-root (&rest body)
60    "Set the default directory to the Rails root directory while
61  BODY is executed."
62    (let ((root (gensym)))
63      `(rails-project:with-root
64        (,root)
65        (let ((default-dir ,root))
66          ,@body))))
67  
68  (defun rails-project:name ()
69    "Return the name of current Rails project."
70    (replace-regexp-in-string "^.*/\\(.*\\)/$" "\\1"
71            (directory-name (rails-project:root))))
72  
73  (provide 'rails-project)