Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 1-3 of 3 total  RSS 

response caching in camping

A basic implementation of response caching in camping.

Camping.goes :MyCampingApp

module MyCampingApp
  module Controller
    class View < R '/'
      def get
        cache('root') do
          'Expensive operation!'
        end
      end
    end
  end
  
  def flush(id)
    f = File.dirname(__FILE__) + "/cache/#{id}"
    File.delete(f) if File.exists?(f)
  end
  
  def cache(id, timeout = 1.hour)
    f = File.dirname(__FILE__) + "/cache/#{id}"
    
    if File.exists?(f) && (Time.now - File.stat(f).mtime) < timeout
      File.read(f)
    else
      r = yield
      open(f, 'w'){|wr| wr.write(r)}
      r
    end
  end

  def self.create
    cache_dir = File.dirname(__FILE__) + "/cache"
    Dir.mkdir(cache_dir) unless File.directory?(cache_dir)
  end
end

Fix for camping multipart parsing issue.

// description of your code here
I wrote a nice description of this issue, but snippets ate it.

In short, this parses complicated form names into nice hashes, i.e. name[asd][asd] for multipart forms.

module Camping
module Base
 def initialize(r, e, m) #:nodoc:
      e = H[e.to_hash]
      @status, @method, @env, @headers, @root = 200, m.downcase, e,
          {'Content-Type'=>'text/html'}, e.SCRIPT_NAME.sub(/\/$/,'')
      @k = C.kp(e.HTTP_COOKIE)
      qs = C.qs_parse(e.QUERY_STRING)
      @in = r
      todo = []
      if %r|\Amultipart/form-data.*boundary=\"?([^\";,]+)|n.match(e.CONTENT_TYPE)
        b = /(?:\r?\n|\A)#{Regexp::quote("--#$1")}(?:--)?\r$/
        until @in.eof?
          fh=H[]
          for l in @in
            case l
            when Z: break
            when /^Content-Disposition: form-data;/
              fh.u H[*$'.scan(/(?:\s(\w+)="([^"]+)")/).flatten]
            when /^Content-Type: (.+?)(\r$|\Z)/m
              puts "=> fh[type] = #$1"
              fh[:type] = $1
            end
          end
          fn=fh[:name]
          o=if fh[:filename]
            o=fh[:tempfile]=Tempfile.new(:C)
            o.binmode
          else
            fh=""
          end
          while l=@in.read(16384)
            if l=~b
              o<<$`.chomp
              @in.seek(-$'.size,IO::SEEK_CUR)
              break
            end
            o<< l
          end
          if(fn)
            qs.merge!(C.qs_parse(fn + "=1"))
            parts = fn.split(/\[/)
            line = ""
            parts.each do |pp|
              pp = pp.gsub(/\]/,"")
              line += "['#{pp}']"
            end
            #p "line is:"
            #p line
            #p fh
            todo << ["qs#{line}", fh]
            #eval("qs#{line} = fh")
            #p qs
          end
          fh[:tempfile].rewind if fh.is_a?H
        end
      elsif @method == "post"
        qs.merge!(C.qs_parse(@in.read))
      end
      #post process vars
      todo.each do |n|
        eval("#{n.first} = n.last")
      end
      #p "END QUERY"
      #p qs
      #exit
      @cookies, @input = @k.dup, qs.dup
    end


end 
end
// insert code here..

The Camping Short, Short Example

Camping encourages short, elegant applications. In this example, we're going to skip the database and put together a simple home page with a few of your favorite links.

The site can be stored in a single file called home_page.rb:

 #!/usr/local/bin/ruby -rubygems
 require 'camping'

 module Camping::Controllers

   # The root slash shows the `index' view.
   class Index < R '/'
     def get
       render :index 
     end
   end

   # Any other page name gets sent to the view
   # of the same name.
   #
   #   /index -> Views#index
   #   /sample -> Views#sample
   #
   class Page < R '/(\w+)'
     def get(page_name)
       render page_name
     end
   end

 end

 module Camping::Views

   # If you have a `layout' method like this, it
   # will wrap the HTML in the other methods.  The
   # `self << yield' is where the HTML is inserted.
   def layout
     html do
       title { 'My HomePage' }
       body { self << yield }
     end
   end

   # The `index' view.  Inside your views, you express
   # the HTML in Ruby.  See http://code.whytheluckystiff.net/markaby/.
   def index
     p 'Hi my name is Charles.'
     p 'Here are some links:'
     ul do
      li { a 'Google', :href => 'http://google.com' }
      li { a 'A sample page', :href => '/sample' }
     end
   end

   # The `sample' view.
   def sample
     p 'A sample page'
   end
 end

 if __FILE__ == $0
   puts Camping.run
 end


Source: The Camping Short, Short Example
« Newer Snippets
Older Snippets »
Showing 1-3 of 3 total  RSS