Skip to content
Browse files

Add convenience fns to util for converting between Java and Clojure i…

…dentifiers in maps, targeted for new capabilities handling
  • Loading branch information...
1 parent 178a966 commit 9916163a9371476d43be53c498a911bfbbc3846e @semperos committed Oct 5, 2012
Showing with 34 additions and 1 deletion.
  1. +34 −1 src/clj_webdriver/util.clj
View
35 src/clj_webdriver/util.clj
@@ -1,6 +1,7 @@
(ns clj-webdriver.util
(:require [clojure.string :as str]
[clojure.java.io :as io]
+ [clojure.walk :as walk]
[clj-webdriver.cache :as cache])
(:import clj_webdriver.driver.Driver
[org.openqa.selenium WebDriver WebElement]
@@ -283,4 +284,36 @@
(defn read-config
[f]
(with-open [r (io/reader f)]
- (read (PushbackReader. r))))
+ (read (PushbackReader. r))))
+
+(defn dashes-to-camel-case
+ "A simple conversion of `-x` to `X` for the given string."
+ [s]
+ (reduce (fn [state item]
+ (.replaceAll state item
+ (str/upper-case (str (second item)))))
+ s
+ (distinct (re-seq #"-[^-]" s))))
+
+(defn camel-case-to-dashes
+ "Convert Pascal-case to dashes. This takes into account edge cases like `fooJSBar` and `fooBarB`, where dashed versions will be `foo-jS-bar` and `foo-barB` respectively."
+ [s]
+ (reduce (fn [state item]
+ (.replaceFirst state item
+ (str "-" (str/lower-case (first item)) (second item))))
+ s
+ (re-seq #"[A-Z](?![A-Z]|$)" s)))
+
+(defn clojure-keys
+ "Recursively transforms all map keys from strings to keywords, converting Pascal-case to dash-separated."
+ [m]
+ (let [f (fn [[k v]] (if (string? k) [(keyword (camel-case-to-dashes k)) v] [k v]))]
+ ;; only apply to maps
+ (walk/postwalk (fn [x] (if (map? x) (into {} (map f x)) x)) m)))
+
+(defn java-keys
+ "Recursively transforms all map keys from keywords into strings, converting dash-separated to Pascal-case."
+ [m]
+ (let [f (fn [[k v]] (if (keyword? k) [(dashes-to-camel-case (name k)) v] [k v]))]
+ ;; only apply to maps
+ (walk/postwalk (fn [x] (if (map? x) (into {} (map f x)) x)) m)))

0 comments on commit 9916163

Please sign in to comment.
Something went wrong with that request. Please try again.