Skip to content

Commit

Permalink
Synched camping and unabridged by using rake diff. Used attr_reader…
Browse files Browse the repository at this point in the history
… instead

of @Ivars whenever possible. camping.rb:4064 -> 4056
  • Loading branch information
Jonas Pfenniger committed Sep 24, 2007
1 parent 1b674e6 commit 0777ceb
Show file tree
Hide file tree
Showing 3 changed files with 118 additions and 96 deletions.
42 changes: 32 additions & 10 deletions Rakefile
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ RDOC_OPTS = ['--quiet', '--title', "Camping, the Documentation",
"--inline-source"]

desc "Packages up Camping."
task :default => [:size, :package]
task :default => [:check]
task :package => [:clean]

task :doc => [:before_doc, :rdoc, :after_doc]
Expand Down Expand Up @@ -128,15 +128,37 @@ task :diff do
sh "diff -u .camping-unabridged.pt .camping.pt | less"
end

SIZE_LIMIT = 4096
desc "Compare camping sizes to unabridged"
task :size do
FileList["lib/camping*.rb"].each do |path|
s = File.size(path)
puts "%21s : % 6d % 4d%" % [File.basename(path), s, (100 * s / SIZE_LIMIT)]
task :check => ["check:valid", "check:size", "check:lines"]
namespace :check do

desc "Check source code validity"
task :valid do
ruby "-w", "lib/camping-unabridged.rb"
ruby "-w", "lib/camping.rb"
end
if File.size("lib/camping.rb") > SIZE_LIMIT
STDERR.puts "ERROR: camping.rb is too big (> #{SIZE_LIMIT})"
exit 1

SIZE_LIMIT = 4096
desc "Compare camping sizes to unabridged"
task :size do
FileList["lib/camping*.rb"].each do |path|
s = File.size(path)
puts "%21s : % 6d % 4d%" % [File.basename(path), s, (100 * s / SIZE_LIMIT)]
end
if File.size("lib/camping.rb") > SIZE_LIMIT
STDERR.puts "lib/camping.rb: file is too big (> #{SIZE_LIMIT})"
exit 1
end
end

desc "Verify that line lenght doesn't exceed 80 chars for camping.rb"
task :lines do
i = 1
File.open("lib/camping.rb").each_line do |line|
if line.size > 81 # 1 added for \n
puts "lib/camping.rb:#{i}: line too long (#{line[-10..-1].inspect})"
end
i += 1
end
end

end
65 changes: 33 additions & 32 deletions lib/camping-unabridged.rb
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@
# http://rubyforge.org/projects/mongrel Mongrel comes with examples
# in its <tt>examples/camping</tt> directory.
#
%w[active_support markaby tempfile uri].each { |lib| require lib }
%w[active_support markaby tempfile uri].map { |l| require l }

# == Camping
#
Expand Down Expand Up @@ -91,6 +91,7 @@ module Camping
# Camping::Apps # => [Blog, Tepee]
#
C = self
f=__FILE__
S = IO.read(f) unless f =~ /\(/
P="Cam\ping Problem!"

Expand Down Expand Up @@ -364,7 +365,7 @@ def redirect(*a)
#
# redirect "/view/12"
#
def r(s, b, h = {}); @status = s; @headers.merge!(h); @body = b; end
def r(s, b, h = {}); @status = s; headers.merge!(h); @body = b; end

# Turn a controller into an array. This is designed to be used to pipe
# controllers into the <tt>r</tt> method. A great way to forward your
Expand All @@ -378,26 +379,25 @@ def r(s, b, h = {}); @status = s; @headers.merge!(h); @body = b; end
# end
# end
#
def to_a;[@status, @body, @headers] end
def to_a;[status, body, headers] end

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.qsp(e.QUERY_STRING)
q = C.qsp(e.QUERY_STRING)
@in = r
if %r|\Amultipart/form-data.*boundary=\"?([^\";,]+)|n.match(e.CONTENT_TYPE)
if %r|\Amultipart/form-.*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;/
when /^Content-D.+?: form-data;/
fh.u H[*$'.scan(/(?:\s(\w+)="([^"]+)")/).flatten]
when /^Content-Type: (.+?)(\r$|\Z)/m
puts "=> fh[type] = #$1"
fh[:type] = $1
end
end
Expand All @@ -420,13 +420,13 @@ def initialize(r, e, m) #:nodoc:
o<<k.slice!(0...s)
[email protected](s)
end
C.qsp(fn,'&;',fh,qs) if fn
C.qsp(fn,'&;',fh,q) if fn
fh[:tempfile].rewind if fh.is_a?H
end
elsif @method == "post" and e.CONTENT_TYPE == "application/x-www-form-urlencoded"
qs.merge!(C.qsp(@in.read))
q.u(C.qsp(@in.read))
end
@cookies, @input = @k.dup, qs.dup
@cookies, @input = @k.dup, q.dup
end
# All requests pass through this method before going to the controller. Some magic
Expand All @@ -436,14 +436,14 @@ def initialize(r, e, m) #:nodoc:
# on before and after overrides with Camping.
def service(*a)
@body = send(@method, *a) if respond_to? @method
@headers['Set-Cookie'] = @cookies.map { |k,v| "#{k}=#{C.escape(v)}; path=#{self/"/"}" if v != @k[k] } - [nil]
headers['Set-Cookie'] = cookies.map { |k,v| "#{k}=#{C.escape(v)}; path=#{self/"/"}" if v != @k[k] } - [nil]
self
end
# Used by the web server to convert the current request to a string. If you need to
# alter the way Camping builds HTTP headers, consider overriding this method.
def to_s
"Status: #{@status}#{Z+@headers.map{|k,v|[*v].map{|x|[k,v]*": "}}*Z+Z*2}#{@body}"
"Status: #{status}#{Z+headers.map{|k,v|[*v].map{|x|[k,v]*": "}}*Z+Z*2}#{body}"
end
end
Expand All @@ -467,7 +467,7 @@ def to_s
# There are two special classes used for handling 404 and 500 errors. The
# NotFound class handles URLs not found. The ServerError class handles exceptions
# uncaught by your application.
module Controllers
X = module Controllers
@r = []
class << self
def r #:nodoc:
Expand Down Expand Up @@ -511,13 +511,13 @@ def R *u
# # Classes with routes are searched in order of their creation.
#
# So, define your catch-all controllers last.
def D(path)
def D(p)
r.map { |k|
k.urls.map { |x|
return k, $~[1..-1] if path =~ /^#{x}\/?$/
return k, $~[1..-1] if p =~ /^#{x}\/?$/
}
}
[NotFound, [path]]
[NotFound, [p]]
end
# The route maker, this is called by Camping internally, you shouldn't need to call it.
Expand Down Expand Up @@ -558,7 +558,7 @@ def M #:nodoc:
#
class NotFound < R()
def get(p)
r(404, Mab.new{h1(P);h2("#{p} not found")})
r(404, Mab.new{h1(P);h2 p + " not found"})
end
end
Expand Down Expand Up @@ -592,11 +592,12 @@ def get(k,m,e)
h2 "#{k}.#{m}"
h3 "#{e.class} #{e.message}:"
ul { e.backtrace.each { |bt| li bt } }
}.to_s)
})
end
end
self
end
X = Controllers
class << self
# When you are running many applications, you may want to create independent
Expand Down Expand Up @@ -640,9 +641,9 @@ def un(s); s.tr('+', ' ').gsub(/%([\da-f]{2})/in){[$1].pack('H*')} end
# input = Camping.qsp("post[id]=1&post[user]=_why")
# #=> {'post' => {'id' => '1', 'user' => '_why'}}
#
def qsp(qs, d='&;', y=nil, z=H[])
def qsp(q, d='&;', y=nil, z=H[])
m = proc {|_,o,n|o.u(n,&m)rescue([*o]<<n)}
(qs||'').
q.to_s.
split(/[#{d}]+ */n).
inject((b,z=z,H[])[0]) { |h,p| k, v=un(p).split('=',2)
h.u(k.split(/[\]\[]+/).reverse.
Expand Down Expand Up @@ -708,6 +709,15 @@ def method_missing(m, c, *a)
end
end
# Views is an empty module for storing methods which create HTML. The HTML is described
# using the Markaby language.
#
# == Using the layout method
#
# If your Views module has a <tt>layout</tt> method defined, it will be called with a block
# which will insert content from your view.
module Views; include X, Helpers end
# Models is an empty Ruby module for housing model classes derived
# from ActiveRecord::Base. As a shortcut, you may derive from Base
# which is an alias for ActiveRecord::Base.
Expand Down Expand Up @@ -737,24 +747,15 @@ module Models
autoload :Base,'camping/db'
def Y;self;end
end
# Views is an empty module for storing methods which create HTML. The HTML is described
# using the Markaby language.
#
# == Using the layout method
#
# If your Views module has a <tt>layout</tt> method defined, it will be called with a block
# which will insert content from your view.
module Views; include Controllers, Helpers end
# The Mab class wraps Markaby, allowing it to run methods from Camping::Views
# and also to replace :href, :action and :src attributes in tags by prefixing the root
# path.
class Mab < Markaby::Builder
include Views
def tag!(*g,&b)
h=g[-1]
[:href,:action,:src].each{|a|(h[a]=self/h[a])rescue 0}
[:href,:action,:src].map{|a|(h[a]=self/h[a])rescue 0}
super
end
end
Expand Down
107 changes: 53 additions & 54 deletions lib/camping.rb
Original file line number Diff line number Diff line change
@@ -1,54 +1,53 @@
%w[active_support markaby tempfile uri].map{|l|require l}
module Camping;C=self;f=__FILE__;S=IO.read(f)unless f=~/\(/
P="Cam\ping Problem!";module Helpers;def R(c,*g);p,h=/\(.+?\)/,g.grep(Hash)
(g-=h).inject(c.urls.find{|x|x.scan(p).size==g.size}.dup){|s,a|s.sub p,C.
escape((a[a.class.primary_key]rescue a))}+(h.any?? "?"+h[0].map{|x|x.map{|z|C.
escape z}*"="}*"&": "")end;def URL c='/',*a;c=R(c,*a)if c.respond_to?:urls
c=self/c;c="//"+@env.HTTP_HOST+c if c[/^\//];URI(c)end;def/p;p[/^\//]?@root+p :
p end;def errors_for o;ul.errors{o.errors.each_full{|x|li x}}if o.errors.any?end
end;module Base;attr_accessor:input,:cookies,:env,:headers,:body,
:status,:root;def method_missing*a,&b;a.shift if a[0]==:render;m=Mab.new({},self)
s=m.capture{send(*a,&b)};s=m.capture{send(:layout){s}}if /^_/!~a[0].to_s and m.
respond_to?:layout;s end;def r s,b,h={};@status=s;@headers.merge!h;@body=b end
def redirect*a;r 302,'','Location'=>URL(*a)end;Z="\r\n";def to_a;[@status,@body,
@headers]end;def initialize r,e,m;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;q=C.qsp e.QUERY_STRING;@in=r;if%r|\Amultipart/form-.*boun\
dary=\"?([^\";,]+)|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-D.+?: form-data;/;fh.u H[*$'.scan(/(?:\s(\w+)="([^"]+)")/).flatten]
when/^Content-Type: (.+?)(\r$|\Z)/m;fh[:type]=$1;end;end;fn=fh[:name];o=if
fh[:filename];o=fh[:tempfile]=Tempfile.new(:C);o.binmode;else;fh=""end;s=8192;k=
'';l=@in.read(s*2);while l;if(k<<l)=~b;o<<$`.chomp;@in.seek(-$'.size,
IO::SEEK_CUR);break;end;o<<k.slice!(0...s);[email protected](s)
end;C.qsp(fn,'&;',fh,q)if fn;fh[:tempfile].rewind if fh.is_a?H;end;elsif@method==
"post" and e.CONTENT_TYPE == "application/x-www-form-urlencoded"
q.u C.qsp(@in.read)end;@cookies,@[email protected],q.dup end;def service*a
@body=send(@method,*a)if respond_to?@method;@headers["Set-Cookie"][email protected]{
|k,v|"#{k}=#{C.escape(v)}; path=#{self/'/'}"if v!=@k[k]}-[nil];self end;def to_s
"Status: #{@status}#{Z+@headers.map{|k,v|[*v].map{|x|[k,v]*": "}}*Z+Z*2}#{@body}"
end;end;X=module Controllers;@r=[];class<<self;def r;@r;end;def R*u
r=@r;Class.new{meta_def(:urls){u};meta_def(:inherited){|x|r<<x}}end;def M;def M
end;constants.map{|c|k=const_get(c);k.send:include,C,Base,Helpers,Models;r[0,0]=k if
!r.include?k;k.meta_def(:urls){["/#{c.downcase}"]}if !k.respond_to?:urls}end;def
D p;r.map{|k|k.urls.map{|x|return k,$~[1..-1]if p=~/^#{x}\/?$/}};[NotFound,[p]]end
end;class NotFound<R();def get p;r(404,Mab.new{h1 P;h2 p+" not found"})end end
class ServerError<R();def get k,m,e;r(500,Mab.new{h1 P;h2"#{k}.#{m}";h3"#{e.class
} #{e.message}:";ul{e.backtrace.each{|bt|li(bt)}}}.to_s)end end;self;end;class<<
self;def goes m;eval S.gsub(/Camping/,m.to_s),TOPLEVEL_BINDING;end;def escape s
s.to_s.gsub(/[^ \w.-]+/n){'%'+($&.
unpack('H2'*$&.size)*'%').upcase}.tr(' ','+')end;def un s;s.tr('+',' ').gsub(
/%([\da-f]{2})/in){[$1].pack('H*')}end;def qsp q,d='&;',y=nil,z=H[];m=proc{|_,o,n|o.u(
n,&m)rescue([*o]<<n)};q.to_s.split(/[#{d}]+ */n).inject((b,z=z,H[])[0]){|h,p|k,v=un(p).
split('=',2);h.u k.split(/[\]\[]+/).reverse.inject(y||v){|x,i|H[i,x]},&m}end;def
kp s;c=qsp(s,';,')end;def run r=$stdin,e=ENV;X.M;k,a=X.D un("/#{e[
'PATH_INFO']}".gsub(/\/+/,'/'));k.new(r,e,(m=e['REQUEST_METHOD']||"GET")).Y.service(*a);
rescue=>x;X::ServerError.new(r,e,'get').service(k,m,x)end
def method_missing m,c,*a;X.M;k=X.const_get(c).new(StringIO.new,H['HTTP_HOST',
'','SCRIPT_NAME','','HTTP_COOKIE',''],m.to_s);H.new(a.pop).each{|e,f|k.send(
"#{e}=",f)}if Hash===a[-1];k.service(*a);end;end;module Views;include X,Helpers
end;module Models;autoload:Base,'camping/db';def Y;self;end;end;class Mab<
Markaby::Builder;include Views;def tag!*g,&b;h=g[-1];[:href,:action,:src].map{
|a|(h[a]=self/h[a])rescue 0};super end end;H=HashWithIndifferentAccess;class H
def method_missing m,*a;m.to_s=~/=$/?self[$`]=a[0]:a==[]?self[m]:super end
alias u regular_update;end end
%w[active_support markaby tempfile uri].map{|l|require l};module Camping;C=self
f=__FILE__;S=IO.read(f)unless f=~/\(/;P="Cam\ping Problem!";H=
HashWithIndifferentAccess;class H;def method_missing m,*a;m.to_s=~/=$/?self[$`
]=a[0]:a==[]?self[m]:super end;alias u regular_update;end;module Helpers
def R c,*g;p,h=/\(.+?\)/,g.grep(Hash);(g-=h).inject(c.urls.find{|x|x.scan(p).
size==g.size}.dup){|s,a|s.sub p,C.escape((a[a.class.primary_key]rescue a))}+(
h.any?? "?"+h[0].map{|x|x.map{|z|C.escape z}*"="}*"&": "")end;def errors_for o
ul.errors{o.errors.each_full{|er|li er}}if o.errors.any?end;def /(p);p[/^\//]?
@root+p:p end;def URL c='/',*a;c=R(c,*a)if c.respond_to?:urls;c=self/c;c="//"+
@env.HTTP_HOST+c if c[/^\//];URI(c) end end;module Base;attr_accessor:input,
:cookies,:env,:headers,:body,:status,:root;Z="\r\n";def method_missing*a,&b;a.
shift if a[0]==:render;m=Mab.new({},self);s=m.capture{send(*a,&b)};s=m.capture{
send(:layout){s}}if /^_/!~a[0].to_s and m.respond_to?:layout;s end;def
redirect*a;r 302,'','Location'=>URL(*a)end;def r s,b,h={};@status=s;headers.
merge!h;@body=b end;def to_a;[status,body,headers]end;def initialize r,e,m;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
q=C.qsp e.QUERY_STRING;@in=r;if%r|\Amultipart/form-.*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-D.+?: form-data;/
fh.u H[*$'.scan(/(?:\s(\w+)="([^"]+)")/).flatten];when
/^Content-Type: (.+?)(\r$|\Z)/m;fh[:type]=$1;end;end;fn=fh[:name];o=if fh[
:filename];o=fh[:tempfile]=Tempfile.new(:C);o.binmode;else;fh=""end;s=8192;k=''
l=@in.read(s*2);while l;if(k<<l)=~b;o<<$`.chomp;@in.seek(-$'.size,IO::SEEK_CUR)
break;end;o<<k.slice!(0...s);[email protected](s);end;C.qsp(fn,'&;',fh,q)if fn;fh[
:tempfile].rewind if fh.is_a?H;end;elsif@method=="post" && e.CONTENT_TYPE==
"application/x-www-form-urlencoded";q.u C.qsp(@in.read)end;@cookies,@input=@k.
dup,q.dup end;def service*a;@body=send(@method,*a)if respond_to?@method
headers["Set-Cookie"]=cookies.map{|k,v|"#{k}=#{C.escape v}; path=#{self/'/'}"if
v!=@k[k]}-[nil];self end;def to_s;"Status: #{status}#{Z+headers.map{|k,v|[*v].
map{|x|[k,v]*": "}}*Z+Z*2}#{body}"end;end;X=module Controllers;@r=[];class<<
self;def r;@r;end;def R*u;r=@r;Class.new{meta_def(:urls){u};meta_def(:inherited
){|x|r<<x}}end;def D p;r.map{|k|k.urls.map{|x|return k,$~[1..-1]if p=~/^#{x
}\/?$/}};[NotFound,[p]]end;def M;def M;end;constants.map{|c|k=const_get(c);k.
send:include,C,Base,Helpers,Models;r[0,0]=k if !r.include?k;k.meta_def(:urls){[
"/#{c.downcase}"]}if !k.respond_to?:urls}end;end;class NotFound<R();def get p
r(404,Mab.new{h1 P;h2 p+" not found"})end end;class ServerError<R();def get k,
m,e;r(500,Mab.new{h1 P;h2"#{k}.#{m}";h3"#{e.class} #{e.message}:";ul{e.
backtrace.each{|bt|li bt}}})end end;self;end;class<<self;def goes m;eval S.
gsub(/Camping/,m.to_s),TOPLEVEL_BINDING;end;def escape s;s.to_s.gsub(
/[^ \w.-]+/n){'%'+($&.unpack('H2'*$&.size)*'%').upcase}.tr(' ','+')end;def un s
s.tr('+',' ').gsub(/%([\da-f]{2})/in){[$1].pack('H*')}end;def qsp q,d='&;',y=
nil,z=H[];m=proc{|_,o,n|o.u(n,&m)rescue([*o]<<n)};q.to_s.split(/[#{d}]+ */n).
inject((b,z=z,H[])[0]){|h,p|k,v=un(p).split('=',2);h.u k.split(/[\]\[]+/).
reverse.inject(y||v){|x,i|H[i,x]},&m}end;def kp s;c=qsp(s,';,')end;def
run r=$stdin,e=ENV;X.M;k,a=X.D un("/#{e['PATH_INFO']}".gsub(/\/+/,'/'));k.new(
r,e,(m=e['REQUEST_METHOD']||"GET")).Y.service(*a);rescue=>x;X::ServerError.new(
r,e,'get').service(k,m,x)end;def method_missing m,c,*a;X.M;k=X.const_get(c).
new(StringIO.new,H['HTTP_HOST','','SCRIPT_NAME','','HTTP_COOKIE',''],m.to_s);H.
new(a.pop).each{|e,f|k.send("#{e}=",f)}if Hash===a[-1];k.service(*a);end;end
module Views;include X,Helpers;end;module Models;autoload:Base,'camping/db';def
Y;self;end;end;class Mab<Markaby::Builder;include Views;def tag!*g,&b;h=g[-1]
[:href,:action,:src].map{|a|(h[a]=self/h[a])rescue 0};super end end end

0 comments on commit 0777ceb

Please sign in to comment.