ring redirect after login - redirect

(ns ...
(:require [ring.util.response :refer [ response redirect]))
My original code be-all-like
(-> (response "You are now logged in! communist party time!")
(assoc :session new-session)
(assoc :headers {"Content-Type" "text/html"}))
Which worked well, but the user still has to navigate elsewhere manually.
Trying to use http://ring-clojure.github.io/ring/ring.util.response.html#var-redirect
(-> (redirect requri)
(assoc :session new-session)
(assoc :headers {"Content-Type" "text/html"}))
doesn't do anything (aside from returning a blank page).
How can I achieve a redirect to a known uri using ring?

response is return a body.
you code is (response requri),but the param of the funtion reponse is html body,not a uri,you can use the this function
like this
(ns foo
(:require [ring.util.response :as response]))
(def requi "/")
(-> (response/redirect requri)
(assoc :session new-session)
(assoc :headers {"Content-Type" "text/html"}))
ps: if you are writing a web site.the lib-noir is a good way to control the session and other.

ipaomian has the answer.
Wanted to share a nice redirect hack:
(ns foo
(:require [ring.util.response :as response]))
(defn redirect
"Like ring.util.response/redirect but also accepts key value pairs
to assoc to response."
[url & kvs]
(let [resp (response/redirect url)]
(if kvs (apply assoc resp kvs) resp)))
(redirect "/" :session new-session :headers {"Content-Type" "text/html"})

ipaomian is right however mine worked by removing the headers. This is my code:
(:require
[ring.util.response :refer [redirect]])
(defn set-user! [id {session :session}]
(-> (redirect "/home")
(assoc :session (assoc session :user id))))

Related

How to pass the variable name as a string to a function? (ClojureScript)

Description of the situation
I want to make a form template for an element, but they must be dynamically created. The meta data involved in the Component should use the variable-name passed as it's meta-data.
Code
For example,
In the view,
(ns my.app
(:require [my.app.templating :as template])
(defn view-component [nOperacaoExtrato]
[:<>
(template/temp-form nOperacaoExtrato)])
The templating function,
(ns my.app.templating)
(defn temp-form
"Template input"
[dado]
#_(js/console.log (str "meta-data: " (meta #'dado)))
(let [nome-var (:name (meta #'dado))]
[:div.col
[:label
{:for (str "form1_" nome-var)}
"Natureza do Dispendio"]
[:p
{:class "form-control",
:id (str "form1_" nome-var)
:name (str "form1" nome-var)}
dado]]))
The result should be, something like this (because the variable passed is nOperacaoExtrato):
[:div.col
[:label
{:for "form1_re-fin-n-operacao-extrato-prop"}
"Nº da Operação no Extrato"]
[:p
{:class "form-control",
:id "form1_re-fin-n-operacao-extrato-prop",
:name "form1_re-fin-n-operacao-extrato-prop"}
(h/preencher-str nOperacaoExtrato)]]
The issue:
Both of these return null.
(meta #'data)
(meta data)
``
You should probably convert this function to a macro. Let me show you fellow Portuguese speaker:
src/cljs/user.cljc
(ns cljs.user)
(defn temp-form-fn
"Template input"
[dado nome-var]
[:div.col
[:label
{:for (str "form1_" nome-var)}
"Natureza do Dispendio"]
[:p
{:class "form-control",
:id (str "form1_" nome-var)
:name (str "form1" nome-var)}
dado]])
#?
(:clj
(defmacro temp-form
[dado]
`(temp-form-fn ~dado ~(name dado))))
Then in the repl:
cljs.user> (require '[cljs.user :refer-macros [temp-form]])
nil
cljs.user> (let [nOperacaoExtrato 1234]
(temp-form nOperacaoExtrato))
[:div.col
[:label {:for "form1_nOperacaoExtrato"} "Natureza do Dispendio"]
[:p
{:class "form-control",
:id "form1_nOperacaoExtrato",
:name "form1nOperacaoExtrato"}
1234]]

Generating inline javascript with cl-who, parenscript and hunchentoot

I'm trying to generate inline javascript, but I have to put the parenscript code inside (:script) and (str) tags using cl-who. ps, ps*, ps-inline and ps-inline* don't seem to make much difference to the generated js.
Is the usual way to write a macro to avoid code duplication, or is there a better way?
Here's my program:
(in-package #:ps-test)
(defmacro standard-page ((&key title) &body body)
`(with-html-output-to-string (*standard-output* nil :prologue t :indent t)
(:html
:lang "en"
(:head
(:meta :http-equiv "Content-Type"
:content "text/html;charset=utf-8")
(:title ,title)
(:link :type "text/css"
:rel "stylesheet"
:href "/style.css"))
(:body
,#body))))
(defun main ()
(with-html-output (*standard-output* nil :indent t :prologue nil)
(standard-page (:title "Parenscript test")
(:div (str "Hello worldzors"))
(:script :type "text/javascript"
(str (ps (alert "Hello world as well")))))))
(define-easy-handler (docroot :uri "/") ()
(main))
(defun start-ps-test ()
(setf (html-mode) :html5)
(setf *js-string-delimiter* #\")
(start (make-instance 'hunchentoot:easy-acceptor :port 8080)))
(defun stop-ps-test ()
(stop *server*))
(defvar *server* (start-ps-test))
Macros are fine in this use case.
The trick is that macros are expanded in a specific order. Say
you define a js macro: when macroexpansion encounters
with-html-output, the inner call to your macros (js (alert "Ho Ho Ho")) looks like a function call, and is left as-is in the generated
code. If your js macro then expands into (:script ...), then the system will complain that :script is an unknown function (assuming you
didn't actually name a function like that). You should emit an
enclosing (who:htm ...) expression to interpret the code using
CL-WHO's code walker.
(defmacro js (code)
`(who:htm
(:script :type "text/javascript" (who:str (ps:ps ,code)))))
This only works in the context of an enclosing with-html-output.
For inline Javascript, you don't want to have a <script> tag around it,
and you can generally simply use ps-inline:
(who:with-html-output (*standard-output*)
(:a :href (ps:ps-inline (void 0))
"A link where the usual HREF behavior is canceled."))
;; prints:
;;
;; <a href='javascript:void(0)'>A link where the usual HREF behavior is canceled.</a>
But feel free to use a macro if you often do the same thing:
(defmacro link (&body body)
`(who:htm (:a :href #.(ps:ps-inline (void 0)) ,#body)))
(who:with-html-output (*standard-output*) (link "Link"))
;; prints:
;;
;; <a href='javascript:void(0)'>Link</a>

clojure.data.xml and parsing jdbc xml object

I'm attempting to read xml (actual xml type) from a postgres database in clojure, however i'm not sure how to cast the org.postgresql.jdbc4.Jdbc4SQLXML object to something clojure.data.xml can make sense of.
When running (xml/parse ...) on this object i'm getting the following error:
IllegalArgumentException No matching method found: createXMLStreamReader for class com.sun.xml.internal.stream.XMLInputFactoryImpl clojure.lang.Reflector.invokeMatchingMethod (Reflector.java:80)
code below:
(ns clj-xml-dbms.core-test
(:require [clojure.test :refer :all]
[clojure.java.jdbc :as j]
[clojure.data.xml :as xml]
[clj-xml-dbms.core :refer :all])
(:use [clojure.pprint ] ))
(def db-spec {
:classname "org.postgres.Driver"
:subprotocol "postgres"
:subname "//localhost:5432/mydb"
:user "me"
:password "secret"
})
;; get the results of a query
(def results
(let [
sql "select row_id, xml_col from stg.some_table limit 1 "
db-connection (j/get-connection db-spec )
statement (j/prepare-statement db-connection sql)
query-results (j/query db-connection [statement]) ]
(first query-results)))
(pprint results)
;; {:row_id 18627,
;; :xml_col #object[org.postgresql.jdbc4.Jdbc4SQLXML 0x6897f635 "org.postgresql.jdbc4.Jdbc4SQLXML#6897f635"]}
;; obviously clojure.data.xml/parse isn't going to work on that:
(xml/parse (:xml_col results))
;; IllegalArgumentException No matching method found: createXMLStreamReader for class com.sun.xml.internal.stream.XMLInputFactoryImpl clojure.lang.Reflector.invokeMatchingMethod (Reflector.java:80)
I guess i could cast the xml type in the db to a string, but there has to be something cleaner that that i would think. Any tips appreciated, thanks.

How can I use ElephantSQL (Postgresql) with a Clojure app?

I added the ElephantSQL add-on to my cloudbees(?) hosted service and named the DB.
I've seen documentation on the MySQL service, and how to integrate it, but nothing for ElephantSQL.
Do I need environment config settings, or a connection string, or what?
On Heroku, I use DATABASE_URL config variable as my connection string.
We recommend using BoneCP and clojure.java.jdbc:
(ns myapp.db
(:import com.jolbox.bonecp.BoneCPDataSource)
(:import java.net.URI)
(:require [clojure.java.jdbc :as jdbc]
[clojure.string :as string]))
(def url (get (System/getenv) "ELEPHANTSQL_URL" "postgres://localhost/mydb"))
(defn pool [url]
(let [uri (URI. url)
host (.getHost uri)
port (if (pos? (.getPort uri)) (.getPort uri) 5432)
path (.getPath uri)
user-info (or (.getUserInfo uri) ":")
[user password] (string/split user-info #":")]
{:datasource
(doto (BoneCPDataSource.)
(.setJdbcUrl (str "jdbc:postgresql://" host ":" port path))
(.setPartitionCount 1)
(.setMinConnectionsPerPartition 3)
(.setMaxConnectionsPerPartition 10)
(.setUsername user)
(.setPassword password))}))
(def pooled-db (delay (pool url)))
(defn account [id]
(jdbc/query
#pooled-db
["SELECT * FROM accounts WHERE id = ?" id]))

Elisp help. Why does the following snippet fail?

I'm trying to write a little script that notifies me when someone talks to me in erc. So I need to write a funcion that recieves what I presume are two strings, nick and msg so I can hook it. But my test function fails. I have tested growl-notify and the format s-expresions and they work fine but I cant get test to work. I have no idea why is it failing. Any pointers?
(defun growl-notify (&key message)
"Use growl for notifications"
(start-process "growlnotify" "growlnotifications" "growlnotify" "-m " message))
(defun test (nick msg)
(growlnotify :message (format "%s: %s" nick msg)))
(test "Ppop" "something")
It gives the following backtrack, hope it helps.
Debugger entered--Lisp error: (void-function growlnotify)
(growlnotify :message (format "%s: %s" nick msg))
test("oi" "poi")
eval((test "oi" "poi") nil)
eval-last-sexp-1(t)
eval-last-sexp(t)
eval-print-last-sexp()
call-interactively(eval-print-last-sexp nil nil)
recursive-edit()
debug(error (wrong-number-of-arguments (lambda (&key message) "Use growl for notifications" (start-process "growlnotify" "growlnotifications" "growlnotify" "-m " message)) 3))
The error message is Debugger entered--Lisp error: (void-function growlnotify), which tells you that growlnotify isn't defined as a function.
If you look at your code, you'll see that you defined it like this: (defun growl-notify (&key message), which defines a function called growl-notify. A simple typo.