Skip to content

Instantly share code, notes, and snippets.

View mwmitchell's full-sized avatar

Matt Mitchell mwmitchell

View GitHub Profile
(def items
[{:id 1 :parent_id nil :code "ONE"}
{:id 2 :parent_id 3 :code "TWO"}
{:id 3 :parent_id nil :code "THREE"}
{:id 4 :parent_id nil :code "FOUR"}])
(def my-items [1 2])
(def result (magic-fn items my-items))
@mwmitchell
mwmitchell / find_one.clj
Created April 4, 2011 15:31
5 different ways to find a single item in a collection
(use '[clojure.contrib.seq-utils :only [find-first]])
(def items [{:id 100} {:id 200} {:id 2}])
(find-first #(= (:id %) 200) items)
(some #(and (= (:id %) 200) %) items)
(first (filter #(= (:id %) 200) items))
; the function i want to mock,
; in a namespace called "other"
(defn do-something [q callback]
(doseq [n [1 2 3]] (callback n)))
; the function i want to test
(defn top []
(other/do-something "q-arg" (fn [item]
(prn item))))
@mwmitchell
mwmitchell / fql.rb
Created March 26, 2011 21:38
A Minimalist Facebook FQL Client in Ruby
require "rubygems"
require "open-uri"
require "rack/utils"
require "json"
class Fql
class << self
attr_accessor :base_url
end
(defmacro with-query-results [query form]
(sql/with-connection db/conn
(sql/with-query-results rs query form)))
(defmulti select-ux class)
(defmethod select-ux String [s] (str "String => " s))
(prn (select-ux "hello"))
; inspired by ActiveRecord's find_in_batches
; and http://asymmetrical-view.com/2010/10/14/clojure-and-large-result-sets.html
(def *default-fetch-size* 50)
(defn with-query-results-cursor [[sql & params :as sql-params] func]
(transaction
(with-open [stmt (.prepareStatement (connection) sql)]
(doseq [[index value] (map vector (iterate inc 1) params)]
(.setObject stmt index value))
select l.name lname, p.name pname, r.place_type rtype, r.name rname
from locations l
left join geoplanet_places p on p.woeid = l.woeid
left join geoplanet_places r on
(
(p.ancestry LIKE concat('%', '/', r.woeid, '/', '%'))
AND r.language = "ENG" AND r.place_type = "State")
where p.woeid = 2397796;
module Eventable
def events
@events ||= {}
end
def trigger event, *args, &block
if block_given?
self.trigger :"before_#{event}", self
result = yield
self.trigger :"after_#{event}", self
result
(defn hotels []
(->
(sql/outer-join
(sql/project (sql/table {:hc_en_hotels :cooked}) [:id :hotel_id])
(sql/project (sql/table :hotels) [:name])
:left
(sql/where (= :hotels.id :cooked.hotel_id)))
(sql/outer-join
(sql/project (sql/table :locations) [[:name :as :location_name]])
:left