PageRenderTime 53ms CodeModel.GetById 27ms RepoModel.GetById 0ms app.codeStats 0ms

/src/closure/templates/soy.clj

https://github.com/duck1123/closure-templates-clj
Clojure | 66 lines | 54 code | 12 blank | 0 comment | 4 complexity | 2b03dfdd79f9e308294937900ada8d96 MD5 | raw file
  1. (ns #^{:doc "Soy helpers." :author "Roman Scherer"}
  2. closure.templates.soy
  3. (:refer-clojure :exclude (replace))
  4. (:import java.io.File java.net.URL java.net.URI)
  5. (:use [clojure.contrib.def :only (defvar)]
  6. [clojure.string :only (blank? replace)]
  7. [inflections.core :only (camelize underscore)]))
  8. (defvar *directory* "soy"
  9. "The directory on the classpath where the Soy template files are
  10. stored.")
  11. (defvar *extension* "soy"
  12. "The filename extension of a Soy template file.")
  13. (defprotocol Soy
  14. (soy [object] "Make a Soy. Returns a java.net.URL instance or throws
  15. an IllegalArgumentException if object is not a Soy."))
  16. (defn soy?
  17. "Returns true if the resource ends with '.soy', otherwise false."
  18. [resource] (.endsWith (str resource) (str "." *extension*)))
  19. (defn soy-seq
  20. "Returns a seq of java.net.URL objects that contains all Soy
  21. template files found in directory."
  22. [directory] (map soy (filter soy? (file-seq (File. (str directory))))))
  23. (defn fn-js
  24. "Returns the template name by replacing all '/' characters with a
  25. '.' and camelizing the names between dots."
  26. [name & [ns]] {:pre [(not (blank? (str name)))]}
  27. (camelize (replace (str (or ns *ns*) "/" name) "/" ".") :lower))
  28. (defn fn-path
  29. "Returns the filename of the template relative to the classpath."
  30. [name & [ns]] {:pre [(not (blank? (str name)))]}
  31. (str *directory* File/separator
  32. (replace (underscore (str (or ns *ns*))) #"\." File/separator)
  33. "." *extension*))
  34. (extend-type Object
  35. Soy
  36. (soy [object]
  37. (throw (IllegalArgumentException. (str "Not a Soy: " object)))))
  38. (extend-type File
  39. Soy
  40. (soy [file]
  41. (if (.exists file)
  42. (soy (.toURL file))
  43. (throw (IllegalArgumentException. (str "Soy doesn't exist: " file))))))
  44. (extend-type String
  45. Soy
  46. (soy [string] (soy (File. string))))
  47. (extend-type URI
  48. Soy
  49. (soy [uri] (.toURL uri)))
  50. (extend-type URL
  51. Soy
  52. (soy [url]
  53. (if (soy? url)
  54. url (throw (IllegalArgumentException. (str "Not a Soy: " url))))))