Leon.Radley.se
  • Blog
  • Labs
  • Projects
  • Leon Radley @ Google+
  • Leon Radley @ GitHub
  • Leon Radley @ Twitter
29 Apr 2013
  • js
  • angular

Angular App in Sub Path using base

When integrating angular into a system that isn't new it's a bit of a struggle trying to get all routes to work and get the initial data in there.

At work we have recently started to integrate Angular with our current applications by serving them up from a sub path, such as: http://myapp.com/admin/survey/123

The problem I faced with this was that I didn't want to have to include /admin/survey/123 in all my routes / links. There must be a better way.

Meet the html base tag

It's not one of the most used html tags but it's great. By adding:

<base href="/admin/survey/123/" />

to the top of your <head> all relative links now are relative to the specified base href.

So a link that would have looked like this <a href="/admin/survey/{{survey.id}}/field/{{field.id}}"></a> can now be shortened to <a href="./field/{{field.id}}"></a>.

Notice the period (.) before the / this is what makes it relative to the base tag and not the the domain.

And the same goes for all the routes. Something that would before look like this:

var prefix = '/admin/survey/123/';

.config(function ($routeProvider, $locationProvider) {
    $locationProvider.html5Mode(true);
 
    routeProvider
    .when(prefix, {
        templateUrl: prefix + 'partial.html',
        controller: 'PartialCtrl'
    })
    .when(prefix + 'index', {
        templateUrl: prefix + 'partial.html',
        controller: 'PartialCtrl'
    })
});

Could now be simplified as this.

.config(function ($routeProvider, $locationProvider) {
    $locationProvider.html5Mode(true);
 
    $routeProvider
    .when('/', {
        templateUrl: 'partial.html',
        controller: 'PartialCtrl'
    })
    .when('/index', {
        templateUrl: 'partial.html',
        controller: 'PartialCtrl'
    })
    .otherwise({
        redirectTo: '/'
    });
});

Base href data

You may ask but how would I get hold of the survey.id or any other survey data.

By creating an Angular constant with the surveyId we can then inject where ever we want.

<script>
    // The @survey variable is coming from play via @(survey: Survey)
    angular.module('app').constant('surveyId', '@survey.id');
</script>

We can then add a main app controller and survey service that loads the survey data as json from /api/admin/survey/123 and injects it into the $rootScope

<!doctype html>
<html ng-app="app" ng-controller="AppCtrl">
<head>
    <!-- again we are using play's variable, but it could be from any backend... -->
    <base href="/admin/survey/@survey.id/" />
    ...
</head>
<body>
    ...
<body>
</html>

And then the AppCtrl and SurveyService

// in SurveyService.js
angular.module('app').factory('SurveyService', function ($resource) {
    return $resource('/api/admin/survey/:surveyId', {surveyId: '@id'});
});

// in AppCtrl.js
angular.module('app').controller('AppCtrl', function ($scope, $rootScope, SurveyService, surveyId) {
    // Notice how we injected the surveyId constant and SurveyService

    $rootScope.survey = SurveyService.get({surveyId: surveyId});
});

Conclusion

By being able to have angular apps live under a sub path and not be bound to that specific path makes your life a lot simpler when you want to use that same app in another project.

Comments
26 Feb 2013
  • play
  • js
  • angular

Play 2.1 Grunt, Angular - Prototype

I've done a Play 2.1 Grunt / Angular prototype that I'd like to share with you.

Preface

Being able to run grunt side by side with play is an awesome setup. Using Less or compass without sluggish rhino. Use coffeescript, typescript, dart... We also get js linting, image compression and more...

Implementation

At the moment this is just a prototype. It hooks on to plays sbt plugins, start and stop commands and fires up grunt and pipes it's commands into sbt.

It also makes npm, bower, yo available at the sbt console, so you never have to leave play to get a new dependency or run yo's scaffolding tasks.

I've set it up so that we have a separate root called ui where the (in this case) angular app will live. It uses the public folder as it's dist output, which means we can then use plays normal Assets controller to include them.

It uses bower to import bootstrap into /ui/components and then we include bootstrap in our main.less file (so that we can use all the awesome mixins)

We also get angular, angular-bootstrap and a couple of shims via bower. By having these in the component.js file we can simply run bower install from the sbt console to get all the components.

When play starts up it also hooks into grunt's watch command (by running grunt dev, which includes the watch command) This means it will start watching less, and js files (all settings are configurable through the Gruntfile.js)

It also starts up live reload, so by installing the live reload plugin for chrome, you can press cmd + s and see the design getting updated straight away without having to do a refresh.

Conclusion

I think this marriage between backend and frontend is a match made in heaven. It will only get better with the coming web components, where it will no longer be possible to go out and fetch the individual components manually.

https://github.com/leon/play-grunt-angular-prototype

Comments
08 Feb 2013
  • play

Play Salat 1.2 Released

I've just published play-salat version 1.2

Version 1.2 comes with:

  • Built against Play 2.1.0 to get all the magic the new stuff.
  • Sample updated to Play 2.1.0 and added JSON Rest example
  • Salat 1.9.2-SNAPSHOT to get scala 2.10, I will release version 1.3 as soon as it's available in release.
  • Mongo Options - Thanks to @ktonga we can now specify loads of settings for our mongo connections. See settings
  • Added JSON Reads and Writes for ObjectId. See example
Comments
07 Feb 2013
  • play

JSON Action Composition

I wanted to share this action with you since it simplifies dealing with incoming json requests a lot.

This is what we want to accomplish.

instead of having to write this.

def create() = Action(parse.json) { implicit request =>
  request.body.validate[User].fold(
    valid = { user =>
      User.save(user)
      Ok(Json.toJson(user))
    },
    invalid = (e => BadRequest(JsError.toFlatJson(e)).as("application/json"))
  )
}

we want to be able to write this.

import controllers.Actions._

// Make sure there is a implicit Reads[User] available...
def create = JsonAction[User] { user =>
  User.save(user)
  Ok(Json.toJson(user))
}

The implementation

This assumes that you have a JSON Reads[A] available as an implicit variable.

See Writing Reads[T] combinators in the documentation.

Start by putting this in a file called Actions.scala in your controllers dir and as you see in the above example we import all the actions defined in that file by writing import controllers.Actions._

package controllers

import play.api.mvc._
import play.api.libs.json._

object Actions extends Results with BodyParsers {

  /**
   * Simplifies handling incoming JSON by wrapping validation and returning BadRequest if it fails
   * @param action the underlying action
   * @tparam A a class that has an implicit Read available
   * @return a response
   */
  def JsonAction[A](action: A => Result)(implicit reader: Reads[A]): EssentialAction = {
    Action(parse.json) { implicit request =>
      request.body.validate[A].fold(
        valid = { json =>
          action(json)
        },
        invalid = (e => BadRequest(JsError.toFlatJson(e)).as("application/json"))
      )
    }
  }
}

Conclusion

Understanding Scala is a lot harder than Java, at least for me, coming from a non functional background. But after completing the on-line course, functional programming in Scala by Martin Odersky, I feel a lot more comfortable in Scala and Play!

Comments
10 Aug 2012
  • akka
Akka command based socket server

Akka command based socket server

Using Akka.IO Iteratees to build a simple socket server.

We start of with the same base as in the Akka IO http sample

class SocketServer(address: InetSocketAddress, addressPromise: Promise[SocketAddress]) extends Actor {

  val state = IO.IterateeRef.Map.async[IO.Handle]()(context.dispatcher)
  val server = IOManager(context.system) listen (address)

  override def postStop() {
    server.close()
    state.keySet foreach (_.close())
  }

  def receive = {
    case Timeout =>
      postStop()

    case IO.Listening(server, address) =>
      addressPromise.success(address)

    case IO.NewClient(server) =>
      import SocketConstants._
      val socket = server.accept()
      state(socket) flatMap (_ => SocketServer.processRequest(socket))

    case IO.Read(socket, bytes) => state(socket)(IO.Chunk(bytes))

    case IO.Closed(socket, cause) =>
      state(socket)(IO.EOF(None))
      state -= socket
  }
}

What this does is enable clients to connect and if there are any bytes arriving on the socket it will get to our SocketServer.processRequest.

This is where the fun starts

Using Iteratees we can manipulate the incomming stream of chars, looking ahead to see what's available with IO.peek or dropping chars we don't care about with IO.drop.

IO.Iteratee Included with Akka’s IO module is a basic implementation of Iteratees. Iteratees are an effective way of handling a stream of data without needing to wait for all the data to arrive. This is especially useful when dealing with non blocking IO since we will usually receive data in chunks which may not include enough information to process, or it may contain much more data then we currently need.

object SocketServer {

  // Import some predefined ByteStrings we have defined
  import SocketConstants._

  def processRequest(implicit socket: IO.SocketHandle): IO.Iteratee[Unit] = {
    // As long as the socket is open keep looking
    IO.repeat {
      // Look at the first four chars and if they match any of the defined command let them continue parsing the stream.
      IO.take(4).flatMap {
        case Exit.command => Exit.read
        case Help.command => Help.read
        case Echo.command => Echo.read
        case Date.command => Date.read
        case Rand.command => Rand.read
        // If no commands match, the Unknown command will consume the rest of the input.
        case _ => Unknown.read
      }
    }
  }
}

A couple of commands

Exit

The Exit command takes everything until it reaches the end of the line. The EOL is simply a shorthand for ByteString("\r\n").

object Exit extends Command {

  val command = ByteString("EXIT")

  def read(implicit socket: IO.SocketHandle) = {
    for {
      _ <- IO takeUntil EOL
    } yield {
      println("Exit")
      socket.close()
    }
  }
}

Echo

The Echo command isn't that different that the exit command, but instead of closing the socket it takes and outputs it back to the socket.

object Echo extends Command {

  val command = ByteString("ECHO")

  def read(implicit socket: IO.SocketHandle) = {
    for {
      all <- IO takeUntil EOL
    } yield {
      println("Echo: " + all)
      socket.write(all ++ EOL)
    }
  }
}

Date

The Date command shows us that we can parse the incoming bytes using nested iteratees.

// Predefined parsers
object SocketIteratees {
  def ascii(bytes: ByteString): String = bytes.decodeString("US-ASCII").trim
  def dateTime(bytes: ByteString): DateTime = DateTime.parse(ascii(bytes), DateTimeFormat.forPattern("yy-MM-dd"))
}

object Date extends Command {

  val command = ByteString("DATE")

  def read(implicit socket: IO.SocketHandle) = {

    import SocketIteratees.dateTime

    for {
      _ <- IO drop 1
      date <- IO takeUntil EOL map dateTime
    } yield {
      println(date)
      socket.write(ByteString(date.toString("yy/MM/dd")) ++ EOL)
    }
  }
}

Fork and try it out

I've created a demo project of the code go try it out.

Comments
03 Mar 2012
  • sublime-text-2
  • textmate-2
  • unix

Sublime Text 2 - rsub

First a little introduction, what is rmate?

I read the blog post about TextMate 2 adding remote editing. By typing rmate myfile on the server, it connects to TextMate 2 via a SSH tunnel making editing a breeze.

Sublime Text 2 now also has this functionality via the rsub plugin (search for rsub via the excellent Package Control) It uses the exact same remote script as TextMate2.

Setup SSH to automatically create the tunnel

In a previous article SSH Tips I wrote about how a couple of lines in a config file can make your life a whole lot easier. The new addition to the ~/.ssh/config file is:

RemoteForward 52698 localhost:52698

As soon as you connect to a server via SSH it will start the remote tunnel.

ssh-copy-rmate

I wanted it to be simple to install the rmate command to the remote server, so I created ssh-copy-rmate. What it does is downloads the latest rmate script from github and via SSH copies it to the file /usr/local/bin/rmate on the server and sets the right permissions.

Since I´m using Sublime Text 2 I also created a clone of the install script called ssh-copy-rsub which names the file on the server to rsub instead of rmate.

Install

  • ssh-copy-rmate if you are using TextMate 2
  • ssh-copy-rsub if you are using Sublime Text 2

and place them in your path or in /usr/local/bin

then run ssh-copy-rsub root@myserver.com

The default is to use the ruby version of the script which requires that you have ruby installed on the server.

If you specify -b (ssh-copy-rsub -b root@myserver.com) it will fetch another version of rmate which doesn't require ruby.

References

  • Sublime Text 2 rsub plugin
  • TextMate 2 rmate feature
  • rmate ruby script
  • rmate shell script
Comments
01 Feb 2012
  • sublime-text-2

Sublime Text 2 - YUI Compressor Plugin

Could't find a plugin for using the YUI Compressor so I wrote one.

The plugin calls the yui-compressor jar file, I've used some settings to avoid putting everything on one single line since most text editors grind to a halt when having to deal with long lines.

java
-jar yuicompressor-2.4.7.jar
--charset utf-8
--preserve-semi
--line-break 150
-o ${file_base_name}-min.${file_extension}

Installation

Use package control http://wbond.net/sublime_packages/package_control and search for YUI Compressor

The source code can be found here: https://github.com/leon/YUI-Compressor

Gettings started

Make sure you have java installed, then open a .js or .css file and press F7 or command + b.

The plugin generates a new file along side the original with the extension .min.js or .min.css

Comments
19 Jan 2012
  • tip
  • unix

SSH Tips

I manage a lot of servers, login in quickly without having to look up passwords or remember which username it was should be simple, I'll show you how simple it can get!.

Below I will give you some tips of how to improve your SSH workflow.

ssh-copy-id is great!

By using ssh-copy-id you connect to the server using secure keys instead of having to use a password.

The syntax of ssh-copy-id is the following:

ssh-copy-id user@server.com

and then it will ask for the password.

it works by copying your public key from ~/.ssh/id_rsa.pub to the servers ~/.ssh/authorized_keys.

And when you then type ssh root@server.com it will first try to connect via secure keys which compares your private key ~/.ssh/id_rsa with the public key you copied with ssh-copy-id before falling back to using passwords.

Generate new key

You can generate your private and public key with the following command:

ssh-keygen -t rsa -b 2048

Simplify further

Now it's time to simplify the ssh command. We still need to specify the user and the host when we connect but by specifying this in the ssh config file we can do away with a lot of typing.

Open the file ~/.ssh/config and put the following in it:

# Stop timing out connections
ServerAliveInterval 300
ServerAliveCountMax 20

# Specify default user
User root

Host myalias
    HostName server.com
    User root

Host myalias2
    HostName server2.com
    User root2

The first is to stop OSX Lion from closing down the connection. (If you don´t specify this, you get Broken pipe syndrome)

I hope this will help you become a better unix hacker :)

Comments
13 Dec 2011
  • mootools

MooTools Carousel

I wrote a 3D carousel in 2006. Back then it was written in the newly released ActionScript 3. But as you all know, flash isn't what all the cool guys use nowadays.

So what I've done is revamp my old code and made it a lot cooler. By using Fx.Spring I could simulate friction.

Try swiping the image. Also try it on the iPad it's touch enabled!

Demo

The tech

By using the new javascript function RequestAnimationFrame I could make it run alot smoother. Otherwise the javascript uses setTimeout(fn, 60) which causes the browser to stall if it can't handle the load.

RequestAnimationFrame handles it differently, it fires your callback whenever your system can handle it.

You also get a bonus, when the browser detects that your tab isn't visible it doesn't fire any RequestAnimationFrame.

Options

options: {
    fps: 20,
    frames: 0,
    autoPlay: true,
    resume: 3000,
    mouse: true,
    inverseMouse: false,
    move: {
        stiffness: 20,
        friction: 10,
        threshold: 0.05
    }
}

Usage

new Carousel('placeholderimageid', 'img/image-sequence{num}.jpg', {
    frames: 36,
    autoPlay: true
});
Comments

Tags

  • play| 3
  • sublime-text-2| 2
  • textmate-2| 1
  • mootools| 1
  • angular| 2
  • akka| 1
  • tip| 1
  • js| 2
  • unix| 2
All content on this site is owned by me, Leon Radley. 2010-2013 ⇪