Changeset 218

Show
Ignore:
Timestamp:
09/24/2007 03:15:27 (14 months ago)
Author:
zimbatm
Message:

Synched camping and unabridged by using rake diff. Used attr_reader instead
of @ivars whenever possible. camping.rb:4064 -> 4056

Location:
trunk
Files:
3 modified

Legend:

Unmodified
Added
Removed
  • trunk/Rakefile

    r212 r218  
    1818 
    1919desc "Packages up Camping." 
    20 task :default => [:size, :package] 
     20task :default => [:check] 
    2121task :package => [:clean] 
    2222 
     
    129129end 
    130130 
    131 SIZE_LIMIT = 4096 
    132 desc "Compare camping sizes to unabridged" 
    133 task :size do 
    134   FileList["lib/camping*.rb"].each do |path| 
    135     s = File.size(path) 
    136     puts "%21s : % 6d % 4d%" % [File.basename(path), s, (100 * s / SIZE_LIMIT)] 
     131task :check => ["check:valid", "check:size", "check:lines"] 
     132namespace :check do 
     133 
     134  desc "Check source code validity" 
     135  task :valid do 
     136    ruby "-w", "lib/camping-unabridged.rb" 
     137    ruby "-w", "lib/camping.rb" 
    137138  end 
    138   if File.size("lib/camping.rb") > SIZE_LIMIT 
    139     STDERR.puts "ERROR: camping.rb is too big (> #{SIZE_LIMIT})" 
    140     exit 1 
     139 
     140  SIZE_LIMIT = 4096 
     141  desc "Compare camping sizes to unabridged" 
     142  task :size do 
     143    FileList["lib/camping*.rb"].each do |path| 
     144      s = File.size(path) 
     145      puts "%21s : % 6d % 4d%" % [File.basename(path), s, (100 * s / SIZE_LIMIT)] 
     146    end 
     147    if File.size("lib/camping.rb") > SIZE_LIMIT 
     148      STDERR.puts "lib/camping.rb: file is too big (> #{SIZE_LIMIT})" 
     149      exit 1 
     150    end 
    141151  end 
     152 
     153  desc "Verify that line lenght doesn't exceed 80 chars for camping.rb" 
     154  task :lines do 
     155    i = 1 
     156    File.open("lib/camping.rb").each_line do |line| 
     157      if line.size > 81 # 1 added for \n 
     158        puts "lib/camping.rb:#{i}: line too long (#{line[-10..-1].inspect})" 
     159      end 
     160      i += 1 
     161    end 
     162  end 
     163 
    142164end 
  • trunk/lib/camping-unabridged.rb

    r216 r218  
    2929# in its <tt>examples/camping</tt> directory.  
    3030# 
    31 %w[active_support markaby tempfile uri].each { |lib| require lib } 
     31%w[active_support markaby tempfile uri].map { |l| require l } 
    3232 
    3333# == Camping  
     
    9292  #  
    9393  C = self 
     94  f=__FILE__ 
    9495  S = IO.read(f) unless f =~ /\(/ 
    9596  P="Cam\ping Problem!" 
     
    365366    #   redirect "/view/12" 
    366367    # 
    367     def r(s, b, h = {}); @status = s; @headers.merge!(h); @body = b; end 
     368    def r(s, b, h = {}); @status = s; headers.merge!(h); @body = b; end 
    368369 
    369370    # Turn a controller into an array.  This is designed to be used to pipe 
     
    379380    #   end 
    380381    # 
    381     def to_a;[@status, @body, @headers] end 
     382    def to_a;[status, body, headers] end 
    382383 
    383384    def initialize(r, e, m) #:nodoc: 
     
    386387          {'Content-Type'=>'text/html'}, e.SCRIPT_NAME.sub(/\/$/,'') 
    387388      @k = C.kp(e.HTTP_COOKIE) 
    388       qs = C.qsp(e.QUERY_STRING) 
     389      q = C.qsp(e.QUERY_STRING) 
    389390      @in = r 
    390       if %r|\Amultipart/form-data.*boundary=\"?([^\";,]+)|n.match(e.CONTENT_TYPE) 
     391      if %r|\Amultipart/form-.*boundary=\"?([^\";,]+)|n.match(e.CONTENT_TYPE) 
    391392        b = /(?:\r?\n|\A)#{Regexp::quote("--#$1")}(?:--)?\r$/ 
    392393        until @in.eof? 
     
    395396            case l 
    396397            when Z: break 
    397             when /^Content-Disposition: form-data;/ 
     398            when /^Content-D.+?: form-data;/ 
    398399              fh.u H[*$'.scan(/(?:\s(\w+)="([^"]+)")/).flatten] 
    399400            when /^Content-Type: (.+?)(\r$|\Z)/m 
    400               puts "=> fh[type] = #$1" 
    401401              fh[:type] = $1 
    402402            end 
     
    421421            l=@in.read(s)  
    422422          end 
    423           C.qsp(fn,'&;',fh,qs) if fn 
     423          C.qsp(fn,'&;',fh,q) if fn 
    424424          fh[:tempfile].rewind if fh.is_a?H 
    425425        end 
    426426      elsif @method == "post" and e.CONTENT_TYPE == "application/x-www-form-urlencoded" 
    427         qs.merge!(C.qsp(@in.read)) 
     427        q.u(C.qsp(@in.read)) 
    428428      end 
    429       @cookies, @input = @k.dup, qs.dup 
     429      @cookies, @input = @k.dup, q.dup 
    430430    end 
    431431 
     
    437437    def service(*a) 
    438438      @body = send(@method, *a) if respond_to? @method 
    439       @headers['Set-Cookie'] = @cookies.map { |k,v| "#{k}=#{C.escape(v)}; path=#{self/"/"}" if v != @k[k] } - [nil] 
     439      headers['Set-Cookie'] = cookies.map { |k,v| "#{k}=#{C.escape(v)}; path=#{self/"/"}" if v != @k[k] } - [nil] 
    440440      self 
    441441    end 
     
    444444    # alter the way Camping builds HTTP headers, consider overriding this method. 
    445445    def to_s 
    446       "Status: #{@status}#{Z+@headers.map{|k,v|[*v].map{|x|[k,v]*": "}}*Z+Z*2}#{@body}" 
     446      "Status: #{status}#{Z+headers.map{|k,v|[*v].map{|x|[k,v]*": "}}*Z+Z*2}#{body}" 
    447447    end 
    448448 
     
    468468  # NotFound class handles URLs not found.  The ServerError class handles exceptions 
    469469  # uncaught by your application. 
    470   module Controllers 
     470  X = module Controllers 
    471471    @r = [] 
    472472    class << self 
     
    512512      # 
    513513      # So, define your catch-all controllers last. 
    514       def D(path) 
     514      def D(p) 
    515515        r.map { |k| 
    516516          k.urls.map { |x| 
    517             return k, $~[1..-1] if path =~ /^#{x}\/?$/ 
     517            return k, $~[1..-1] if p =~ /^#{x}\/?$/ 
    518518          } 
    519519        } 
    520         [NotFound, [path]] 
     520        [NotFound, [p]] 
    521521      end 
    522522 
     
    559559    class NotFound < R() 
    560560      def get(p) 
    561         r(404, Mab.new{h1(P);h2("#{p} not found")}) 
     561        r(404, Mab.new{h1(P);h2 p + " not found"}) 
    562562      end 
    563563    end 
     
    593593          h3 "#{e.class} #{e.message}:" 
    594594          ul { e.backtrace.each { |bt| li bt } } 
    595         }.to_s) 
     595        }) 
    596596      end 
    597597    end 
     598 
     599    self 
    598600  end 
    599   X = Controllers 
    600601 
    601602  class << self 
     
    641642    #     #=> {'post' => {'id' => '1', 'user' => '_why'}} 
    642643    # 
    643     def qsp(qs, d='&;', y=nil, z=H[]) 
     644    def qsp(q, d='&;', y=nil, z=H[]) 
    644645        m = proc {|_,o,n|o.u(n,&m)rescue([*o]<<n)} 
    645         (qs||''). 
     646        q.to_s. 
    646647            split(/[#{d}]+ */n). 
    647648            inject((b,z=z,H[])[0]) { |h,p| k, v=un(p).split('=',2) 
     
    709710  end 
    710711 
     712  # Views is an empty module for storing methods which create HTML.  The HTML is described 
     713  # using the Markaby language. 
     714  # 
     715  # == Using the layout method 
     716  # 
     717  # If your Views module has a <tt>layout</tt> method defined, it will be called with a block 
     718  # which will insert content from your view. 
     719  module Views; include X, Helpers end 
     720  
    711721  # Models is an empty Ruby module for housing model classes derived 
    712722  # from ActiveRecord::Base.  As a shortcut, you may derive from Base 
     
    738748      def Y;self;end 
    739749  end 
    740  
    741   # Views is an empty module for storing methods which create HTML.  The HTML is described 
    742   # using the Markaby language. 
    743   # 
    744   # == Using the layout method 
    745   # 
    746   # If your Views module has a <tt>layout</tt> method defined, it will be called with a block 
    747   # which will insert content from your view. 
    748   module Views; include Controllers, Helpers end 
    749    
     750  
    750751  # The Mab class wraps Markaby, allowing it to run methods from Camping::Views 
    751752  # and also to replace :href, :action and :src attributes in tags by prefixing the root 
     
    755756      def tag!(*g,&b) 
    756757          h=g[-1] 
    757           [:href,:action,:src].each{|a|(h[a]=self/h[a])rescue 0} 
     758          [:href,:action,:src].map{|a|(h[a]=self/h[a])rescue 0} 
    758759          super  
    759760      end 
  • trunk/lib/camping.rb

    r217 r218  
    1 %w[active_support markaby tempfile uri].map{|l|require l} 
    2 module Camping;C=self;f=__FILE__;S=IO.read(f)unless f=~/\(/ 
    3 P="Cam\ping Problem!";module Helpers;def R(c,*g);p,h=/\(.+?\)/,g.grep(Hash) 
    4 (g-=h).inject(c.urls.find{|x|x.scan(p).size==g.size}.dup){|s,a|s.sub p,C. 
    5 escape((a[a.class.primary_key]rescue a))}+(h.any?? "?"+h[0].map{|x|x.map{|z|C. 
    6 escape z}*"="}*"&": "")end;def URL c='/',*a;c=R(c,*a)if c.respond_to?:urls 
    7 c=self/c;c="//"+@env.HTTP_HOST+c if c[/^\//];URI(c)end;def/p;p[/^\//]?@root+p : 
    8 p end;def errors_for o;ul.errors{o.errors.each_full{|x|li x}}if o.errors.any?end 
    9 end;module Base;attr_accessor:input,:cookies,:env,:headers,:body, 
    10 :status,:root;def method_missing*a,&b;a.shift if a[0]==:render;m=Mab.new({},self) 
    11 s=m.capture{send(*a,&b)};s=m.capture{send(:layout){s}}if /^_/!~a[0].to_s and m. 
    12 respond_to?:layout;s end;def r s,b,h={};@status=s;@headers.merge!h;@body=b end 
    13 def redirect*a;r 302,'','Location'=>URL(*a)end;Z="\r\n";def to_a;[@status,@body, 
    14 @headers]end;def initialize r,e,m;e=H[e.to_hash];@status,@method,@env,@headers, 
    15 @root=200,m.downcase,e,{'Content-Type'=>"text/html"},e.SCRIPT_NAME.sub(/\/$/,'') 
    16 @k=C.kp e.HTTP_COOKIE;q=C.qsp e.QUERY_STRING;@in=r;if%r|\Amultipart/form-.*boun\ 
    17 dary=\"?([^\";,]+)|n.match e.CONTENT_TYPE;b=/(?:\r?\n|\A)#{Regexp::quote("--#$1" 
    18 )}(?:--)?\r$/;until@in.eof?;fh=H[];for l in@in;case l;when Z;break 
    19 when/^Content-D.+?: form-data;/;fh.u H[*$'.scan(/(?:\s(\w+)="([^"]+)")/).flatten] 
    20 when/^Content-Type: (.+?)(\r$|\Z)/m;fh[:type]=$1;end;end;fn=fh[:name];o=if 
    21 fh[:filename];o=fh[:tempfile]=Tempfile.new(:C);o.binmode;else;fh=""end;s=8192;k= 
    22 '';l=@in.read(s*2);while l;if(k<<l)=~b;o<<$`.chomp;@in.seek(-$'.size, 
    23 IO::SEEK_CUR);break;end;o<<k.slice!(0...s);l=@in.read(s) 
    24 end;C.qsp(fn,'&;',fh,q)if fn;fh[:tempfile].rewind if fh.is_a?H;end;elsif@method== 
    25 "post" and e.CONTENT_TYPE == "application/x-www-form-urlencoded" 
    26 q.u C.qsp(@in.read)end;@cookies,@input=@k.dup,q.dup end;def service*a 
    27 @body=send(@method,*a)if respond_to?@method;@headers["Set-Cookie"]=@cookies.map{ 
    28 |k,v|"#{k}=#{C.escape(v)}; path=#{self/'/'}"if v!=@k[k]}-[nil];self end;def to_s 
    29 "Status: #{@status}#{Z+@headers.map{|k,v|[*v].map{|x|[k,v]*": "}}*Z+Z*2}#{@body}" 
    30 end;end;X=module Controllers;@r=[];class<<self;def r;@r;end;def R*u 
    31 r=@r;Class.new{meta_def(:urls){u};meta_def(:inherited){|x|r<<x}}end;def M;def M 
    32 end;constants.map{|c|k=const_get(c);k.send:include,C,Base,Helpers,Models;r[0,0]=k if 
    33 !r.include?k;k.meta_def(:urls){["/#{c.downcase}"]}if !k.respond_to?:urls}end;def 
    34 D p;r.map{|k|k.urls.map{|x|return k,$~[1..-1]if p=~/^#{x}\/?$/}};[NotFound,[p]]end 
    35 end;class NotFound<R();def get p;r(404,Mab.new{h1 P;h2 p+" not found"})end end 
    36 class ServerError<R();def get k,m,e;r(500,Mab.new{h1 P;h2"#{k}.#{m}";h3"#{e.class 
    37 } #{e.message}:";ul{e.backtrace.each{|bt|li(bt)}}}.to_s)end end;self;end;class<< 
    38 self;def goes m;eval S.gsub(/Camping/,m.to_s),TOPLEVEL_BINDING;end;def escape s 
    39 s.to_s.gsub(/[^ \w.-]+/n){'%'+($&. 
    40 unpack('H2'*$&.size)*'%').upcase}.tr(' ','+')end;def un s;s.tr('+',' ').gsub( 
    41 /%([\da-f]{2})/in){[$1].pack('H*')}end;def qsp q,d='&;',y=nil,z=H[];m=proc{|_,o,n|o.u( 
    42 n,&m)rescue([*o]<<n)};q.to_s.split(/[#{d}]+ */n).inject((b,z=z,H[])[0]){|h,p|k,v=un(p). 
    43 split('=',2);h.u k.split(/[\]\[]+/).reverse.inject(y||v){|x,i|H[i,x]},&m}end;def 
    44 kp s;c=qsp(s,';,')end;def run r=$stdin,e=ENV;X.M;k,a=X.D un("/#{e[ 
    45 'PATH_INFO']}".gsub(/\/+/,'/'));k.new(r,e,(m=e['REQUEST_METHOD']||"GET")).Y.service(*a); 
    46 rescue=>x;X::ServerError.new(r,e,'get').service(k,m,x)end 
    47 def method_missing m,c,*a;X.M;k=X.const_get(c).new(StringIO.new,H['HTTP_HOST', 
    48 '','SCRIPT_NAME','','HTTP_COOKIE',''],m.to_s);H.new(a.pop).each{|e,f|k.send( 
    49 "#{e}=",f)}if Hash===a[-1];k.service(*a);end;end;module Views;include X,Helpers 
    50 end;module Models;autoload:Base,'camping/db';def Y;self;end;end;class Mab< 
    51 Markaby::Builder;include Views;def tag!*g,&b;h=g[-1];[:href,:action,:src].map{ 
    52 |a|(h[a]=self/h[a])rescue 0};super end end;H=HashWithIndifferentAccess;class H 
    53 def method_missing m,*a;m.to_s=~/=$/?self[$`]=a[0]:a==[]?self[m]:super end 
    54 alias u regular_update;end end 
     1%w[active_support markaby tempfile uri].map{|l|require l};module Camping;C=self 
     2f=__FILE__;S=IO.read(f)unless f=~/\(/;P="Cam\ping Problem!";H= 
     3HashWithIndifferentAccess;class H;def method_missing m,*a;m.to_s=~/=$/?self[$` 
     4]=a[0]:a==[]?self[m]:super end;alias u regular_update;end;module Helpers 
     5def R c,*g;p,h=/\(.+?\)/,g.grep(Hash);(g-=h).inject(c.urls.find{|x|x.scan(p). 
     6size==g.size}.dup){|s,a|s.sub p,C.escape((a[a.class.primary_key]rescue a))}+( 
     7h.any?? "?"+h[0].map{|x|x.map{|z|C.escape z}*"="}*"&": "")end;def errors_for o 
     8ul.errors{o.errors.each_full{|er|li er}}if o.errors.any?end;def /(p);p[/^\//]? 
     9@root+p:p end;def URL c='/',*a;c=R(c,*a)if c.respond_to?:urls;c=self/c;c="//"+ 
     10@env.HTTP_HOST+c if c[/^\//];URI(c) end end;module Base;attr_accessor:input, 
     11:cookies,:env,:headers,:body,:status,:root;Z="\r\n";def method_missing*a,&b;a. 
     12shift if a[0]==:render;m=Mab.new({},self);s=m.capture{send(*a,&b)};s=m.capture{ 
     13send(:layout){s}}if /^_/!~a[0].to_s and m.respond_to?:layout;s end;def 
     14redirect*a;r 302,'','Location'=>URL(*a)end;def r s,b,h={};@status=s;headers. 
     15merge!h;@body=b end;def to_a;[status,body,headers]end;def initialize r,e,m;e=H[ 
     16e.to_hash];@status,@method,@env,@headers,@root=200,m.downcase,e,{ 
     17'Content-Type'=>"text/html"},e.SCRIPT_NAME.sub(/\/$/,'');@k=C.kp e.HTTP_COOKIE 
     18q=C.qsp e.QUERY_STRING;@in=r;if%r|\Amultipart/form-.*boundary=\"?([^\";,]+)|n. 
     19match e.CONTENT_TYPE;b=/(?:\r?\n|\A)#{Regexp::quote"--#$1"}(?:--)?\r$/;until 
     20@in.eof?;fh=H[];for l in@in;case l;when Z;break;when/^Content-D.+?: form-data;/ 
     21fh.u H[*$'.scan(/(?:\s(\w+)="([^"]+)")/).flatten];when 
     22/^Content-Type: (.+?)(\r$|\Z)/m;fh[:type]=$1;end;end;fn=fh[:name];o=if fh[ 
     23:filename];o=fh[:tempfile]=Tempfile.new(:C);o.binmode;else;fh=""end;s=8192;k='' 
     24l=@in.read(s*2);while l;if(k<<l)=~b;o<<$`.chomp;@in.seek(-$'.size,IO::SEEK_CUR) 
     25break;end;o<<k.slice!(0...s);l=@in.read(s);end;C.qsp(fn,'&;',fh,q)if fn;fh[ 
     26:tempfile].rewind if fh.is_a?H;end;elsif@method=="post" && e.CONTENT_TYPE== 
     27"application/x-www-form-urlencoded";q.u C.qsp(@in.read)end;@cookies,@input=@k. 
     28dup,q.dup end;def service*a;@body=send(@method,*a)if respond_to?@method 
     29headers["Set-Cookie"]=cookies.map{|k,v|"#{k}=#{C.escape v}; path=#{self/'/'}"if 
     30v!=@k[k]}-[nil];self end;def to_s;"Status: #{status}#{Z+headers.map{|k,v|[*v]. 
     31map{|x|[k,v]*": "}}*Z+Z*2}#{body}"end;end;X=module Controllers;@r=[];class<< 
     32self;def r;@r;end;def R*u;r=@r;Class.new{meta_def(:urls){u};meta_def(:inherited 
     33){|x|r<<x}}end;def D p;r.map{|k|k.urls.map{|x|return k,$~[1..-1]if p=~/^#{x 
     34}\/?$/}};[NotFound,[p]]end;def M;def M;end;constants.map{|c|k=const_get(c);k. 
     35send:include,C,Base,Helpers,Models;r[0,0]=k if !r.include?k;k.meta_def(:urls){[ 
     36"/#{c.downcase}"]}if !k.respond_to?:urls}end;end;class NotFound<R();def get p 
     37r(404,Mab.new{h1 P;h2 p+" not found"})end end;class ServerError<R();def get k, 
     38m,e;r(500,Mab.new{h1 P;h2"#{k}.#{m}";h3"#{e.class} #{e.message}:";ul{e. 
     39backtrace.each{|bt|li bt}}})end end;self;end;class<<self;def goes m;eval S. 
     40gsub(/Camping/,m.to_s),TOPLEVEL_BINDING;end;def escape s;s.to_s.gsub( 
     41/[^ \w.-]+/n){'%'+($&.unpack('H2'*$&.size)*'%').upcase}.tr(' ','+')end;def un s 
     42s.tr('+',' ').gsub(/%([\da-f]{2})/in){[$1].pack('H*')}end;def qsp q,d='&;',y= 
     43nil,z=H[];m=proc{|_,o,n|o.u(n,&m)rescue([*o]<<n)};q.to_s.split(/[#{d}]+ */n). 
     44inject((b,z=z,H[])[0]){|h,p|k,v=un(p).split('=',2);h.u k.split(/[\]\[]+/). 
     45reverse.inject(y||v){|x,i|H[i,x]},&m}end;def kp s;c=qsp(s,';,')end;def 
     46run r=$stdin,e=ENV;X.M;k,a=X.D un("/#{e['PATH_INFO']}".gsub(/\/+/,'/'));k.new( 
     47r,e,(m=e['REQUEST_METHOD']||"GET")).Y.service(*a);rescue=>x;X::ServerError.new( 
     48r,e,'get').service(k,m,x)end;def method_missing m,c,*a;X.M;k=X.const_get(c). 
     49new(StringIO.new,H['HTTP_HOST','','SCRIPT_NAME','','HTTP_COOKIE',''],m.to_s);H. 
     50new(a.pop).each{|e,f|k.send("#{e}=",f)}if Hash===a[-1];k.service(*a);end;end 
     51module Views;include X,Helpers;end;module Models;autoload:Base,'camping/db';def 
     52Y;self;end;end;class Mab<Markaby::Builder;include Views;def tag!*g,&b;h=g[-1] 
     53[:href,:action,:src].map{|a|(h[a]=self/h[a])rescue 0};super end end end