From 4b07c992d1af1de0303686626e2d11fb397e9653 Mon Sep 17 00:00:00 2001 From: gered Date: Sat, 14 Jun 2014 22:44:08 -0400 Subject: [PATCH] where appropriate, automatically convert string values to keywords when the the string value is going to be used to check/sort against a map key --- src/clj_jtwig/standard_functions.clj | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/src/clj_jtwig/standard_functions.clj b/src/clj_jtwig/standard_functions.clj index f1e4576..1ba15d2 100644 --- a/src/clj_jtwig/standard_functions.clj +++ b/src/clj_jtwig/standard_functions.clj @@ -3,7 +3,14 @@ library and are just here to fill in the gaps for now." (:import (org.apache.commons.lang3.text WordUtils) (org.apache.commons.lang3 StringUtils)) - (:use [clojure.pprint])) + (:use [clojure.pprint] + [clj-jtwig.options])) + +(defn- possible-keyword-string [x] + (if (and (:auto-convert-map-keywords @options) + (string? x)) + (keyword x) + x)) ; we are using a separate map to hold the standard functions instead of using deftwigfn, etc. because doing it this ; way makes it easy to re-add all these functions when/if the JTwig function repository object needs to be @@ -32,7 +39,7 @@ "contains" {:fn (fn [coll value] (if (map? coll) - (contains? coll value) + (contains? coll (possible-keyword-string value)) ; explicit use of '=' to allow testing for falsey values (some #(= value %) coll)))} @@ -146,11 +153,13 @@ "sort_by" {:fn (fn [coll k] - (sort-by #(get % k) coll))} + (let [sort-key (possible-keyword-string k)] + (sort-by #(get % sort-key) coll)))} "sort_descending_by" {:fn (fn [coll k] - (sort-by #(get % k) #(compare %2 %1) coll)) + (let [sort-key (possible-keyword-string k)] + (sort-by #(get % sort-key) #(compare %2 %1) coll))) :aliases ["sort_desc_by"]} "wrap"