session snippets

Testing sessions with Sinatra and Rack::Test

Tagged session, test, sinatra, rack, cookie, rack::test, mocha  Languages ruby

You need support for testing sessions when, for example, testing authentication. The only way I've managed to get sessions to work with Sinatra and Rack::Test is by going through the whole stack, in other words calling the authentication controller as shown here:

@user = Factory(:user) # create a dummy user
User.expects(:authenticate).with(any_parameters).returns(@user) # make authenticate return the dummy user
post "/sign-in", {:email =>, :password => @user.password} # login to the application and set a session variable.

After this the session populated and we're logged in when accessing the application again:

post "/articles", {:title => 'Sessions suck', :body => '...'}

On a side note, there are two ways of specifying sessions that used to work, but which no longer work with Sinatra 1.0:

get '/', :env => { :session => {:abc => 'adf'} }
get '/', {}, :session => {:abc => 'adf'}
get '/', {}, "rack.session" => {:abc => 'adf'}

The session is always empty.

There are many discussions about sessions and Rack::Test, but not one of them has a solution that works for me: * rack.session variable is missing env under test environment * Sessions with rspec and Rack.Test

Rails Cells Example

Tagged rails, cells, request, session, params, controller  Languages ruby

This Rails Cells example demonstrates how to: * access the request * access the controller * access the session * access the request parameters * cache data * use dynamic cache keys * access cell parameters * use helpers

class MenuCell < Cell::Rails
  helper :menu
  cache :display, :cache_conf, :expires_in =>

  def display
    @selected = options[:selected]
    @posts ||= Post.paginate(options[:posts])

    def cache_conf
      # parent_controller.controller_name
      # parent_controller.request or request
      # parent_controller.session
      # parent_controller.params
      { :path => request.fullpath }

The cell is rendered by calling:

<%= render_cell :menu, :display, :selected => controller.controller_name %>

See Cells the change log for details.

How to set the session's time zone to UTC when using Golang's database/sql

Tagged database, golang, session, sql, timestamp  Languages go

Always remember to set the time zone session setting when using database/sql and timestamps, otherwise timestamps will use the database default:

db, err = sql.Open("postgres", "timezone=UTC")
if err != nil {
defer db.Close()
var timezone string
err = db.QueryRow("SHOW timezone").Scan(&timezone)
if err != nil {
log.Println("timezone:", timezone)

Running SET TIME ZONE ‘Africa/Casablanca’; once in a connection won’t work because a pool of connections is used.