Skip to content

Instantly share code, notes, and snippets.

@sam
sam / Actions.scala
Last active December 24, 2015 14:59
Write your Models directly to Actions in Play. Add these implicits to your base Controller, import your spray JsonFormats, and now you can just call BLL methods that return the appropriate types.
object Users extends Controller with JsResultConversions with JsFormats {
def show(id) = Action.async {
api.users.get(id)
}
def update = Action.async {
editForm.fold(_ => Future.successful(BadRequest), api.users.save(_))
}
@sam
sam / Example.scala
Created September 18, 2013 22:50
Scalaz's Applicative Functor for Futures.
// Zip together a couple Futures, including one that returns an Option
// and pass them to a function to give me a new object:
api.channels.tree zip api.pages.getByRoute(route) map {
case (tree, Some(page)) => Some(new PagePresenter(context, tree, page))
case _ => None
}
// Now with an Applicative Functor!
(api.channels.tree |@| api.pages.getByRoute(route)) {
@sam
sam / FunctionalComposition.scala
Created September 5, 2013 15:43
Simple example of a Play Framework / ScalaTest spec using functional composition to keep the building of two similar Requests (only difference is the Request-Method) DRY.
"Delete" taggedAs(tag.RolesTag) in {
val request = (FakeRequest(_:String, "/admin/roles/role-bob")) andThen
withAdminCredentials andThen
(route(_:FakeRequest[AnyContentAsEmpty.type]))
for { result <- request(DELETE) } {
status(result) must equal(SEE_OTHER)
flash(result).data must contain key("deleted")
}
@sam
sam / .gitignore
Last active December 21, 2015 09:19
Implicits in Scala
target
start = Time.now
100.times do
letter_list = []
alphabet = ('a'..'z').to_a
100_000.times{ letter_list << alphabet[rand(26)] }
pick = letter_list.uniq[rand(26)]
before, after = letter_list.partition{|n| n > pick}
end
p (Time.now - start) * 1000
@sam
sam / TopTen.scala
Last active December 19, 2015 15:49
Top Ten Words in a String.
object Main extends App {
val wordCount = "(\\w+)".r
.findAllIn(_:String)
.toSeq
.groupBy(_.toLowerCase)
.mapValues(_.size)
.toSeq
.sortBy(_._2)
.reverse
@sam
sam / sbt-debug
Created June 21, 2013 15:00
sbt-debug script
#!/bin/sh
test -f ~/.sbtconfig && . ~/.sbtconfig
SBT_LAUNCH=/usr/local/Cellar/sbt/0.12.3/libexec/sbt-launch.jar
# Take leading integer as debug port and not sbt args
DEBUG_PORT=$1
SBT_ARGS=`echo "$@" | grep -oE "[^0-9].*"`
exec java -Xmx512M -Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=${DEBUG_PORT} ${SBT_OPTS} -jar $SBT_LAUNCH $SBT_ARGS
@sam
sam / Application.scala
Last active December 18, 2015 16:09
Get rid of Async wrappers in Play Framework Actions. The advantage of this approach over pattern-matching is that it's extensible by downstream code introducing new types, and moves what would otherwise be a runtime error (bad match) to a compiler error (no evidence found).
import play.api.mvc._
import play.api.mvc.{Action => PlayAction}
import scala.concurrent._
object Application extends Controller {
// Define the Type Class that will allow us to coerce our action return-types to Results.
trait RequestHandlerLike[-T] {
def apply(result: T): Result // = result
}
@sam
sam / Benchmark.scala
Created April 10, 2013 16:09
Simple Benchmark from Scala 2.10. For reference since it's deprecated (grr).
/* __ *\
** ________ ___ / / ___ Scala API **
** / __/ __// _ | / / / _ | (c) 2003-2013, LAMP/EPFL **
** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ **
** /____/\___/_/ |_/____/_/ | | **
** |/ **
\* */
package scala.testing
@sam
sam / DatabaseConnection.scala
Last active December 15, 2015 20:58
Basic database interaction using Slick's "sql" String interpolator and returning a tuple for the row.
package models.slick
import com.typesafe.config.ConfigFactory
object DatabaseConnection {
import scala.slick.driver.PostgresDriver.simple._
// Note, I've got a Play-like Scala wrapper for Typesafe's Config library as well, which is a bit cleaner than this.
implicit lazy val database = ConfigFactory.load("conf/database.conf").getConfig("db.default") match { case config =>
Database.forURL(