request snippets

How to print all HTTP headers with PHP

Tagged php, http, headers, request  Languages php
<ul>
 <?php
   foreach($_SERVER as $h=>$v)
     if(ereg('HTTP_(.+)',$h,$hp))
       echo "<li>$h = $v</li>\n";
   header('Content-type: text/html');
  ?>
</ul>

How to parse request parameters with JavaScript

Tagged javascript, jquery, request, parameters, url, parse  Languages javascript

Code:

var Request = {
    parameter: function(name) {
      return this.parameters()[name];
    },
    parameters: function(uri) {
      var i, parameter, params, query, result;
      result = {};
      if (!uri) {
        uri = window.location.search;
      }
      if (uri.indexOf("?") === -1) {
        return {};
      }
      query = uri.slice(1);
      params = query.split("&");
      i = 0;
      while (i < params.length) {
        parameter = params[i].split("=");
        result[parameter[0]] = parameter[1];
        i++;
      }
      return result;
    }
  };

Examples:

// ?query=test
var query = Request.parameter('query');

var parameters = Request.parameters();
// This works too
var query = parameters.query;
// And this
var query = parameters['query'];

// Replacing a parameter is easy with jQuery
parameters Request.parameters();
// change sort order
parameters.order = 'new-world-order'
new_parameters = $.param(parameters)
url = window.location.pathname + "?" + new_parameters

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 => 1.day

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

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

The cell is rendered by calling:

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

See Cells the change log for details.

How to test Sinatra helpers

Tagged request, sinatra, test  Languages ruby

This one depends on a request object (Rack::Request) being present:

class AppHelpersSpec < Test::Unit::TestCase                                            
  include AppHelpers
  include Rack::Test::Methods

  def request
    Rack::Request.new(Rack::MockRequest.env_for '/', {params: {name: 'hohohoe'}})
  end

  def test_helper_method
    res = some_helper_method # call helper method
    assert_equal 'WTF!', res
  end
end

LOL.