Skip to content

Instantly share code, notes, and snippets.

@jo
Created March 31, 2011 20:14
Show Gist options
  • Save jo/897164 to your computer and use it in GitHub Desktop.
Save jo/897164 to your computer and use it in GitHub Desktop.
couch app purism
{
"_id": "_design/myapp",
"rewrites": <%= read 'rewrites.json' %>,
"updates": {
"nash": <%=h read 'updates/entry.js' %>
},
"validate_doc_update": <%=h read 'validate.js' %>,
"views": {
"nashs": {
"map": <%=h read 'couchdb-views/entries/map.js' %>
}
},
"_attachments": {<% combine %w[vendor/*.js models/*.js views/*.js app.js], 'app.js' do |filename, content| %>
"<%= filename %>": {
"content_type": "text/javascript",
"data": <%=h base64 content || uglify(filename) %>
},<% end %>
"style.css": {
"content_type": "text/css",
"data": <%=h base64 strip read 'style.css' %>
},
"index.html": {
"content_type": "text/html",
"data": <%=h base64 strip compile 'index.html.erb' %>
}
}
}
./rounch app.json.erb -cud http://127.0.0.1:5984/myapp
#!/usr/bin/env ruby
# Rouch - couch app purism
# (c) 2011 Johannes J. Schmidt, TF
require 'optparse'
require 'erb'
require 'tempfile'
def read filename
File.read filename
end
def compile filename
ERB.new(read(filename)).result(binding)
end
def combine patterns, target, &block
patterns = [patterns] unless patterns.is_a?(Array)
files = patterns.map { |p| Dir[p].sort }.flatten
if ENV['ROUCH_COMBINE']
block.call(target, files.map { |f| uglify f }.join("\n"))
@js = [target]
else
files.each(&block)
@js = files
end
end
def strip content
content.strip.gsub /\s+/, ' '
end
def base64 content
[content].pack("m").gsub(/\s+/,'')
end
def uglify filename
# TODO: remove -b --beautify
ENV['ROUCH_UGLIFY'] ? `uglifyjs --beautify --indent 0 --quote-keys --no-copyright #{filename}` : read(filename)
end
def h content
content.inspect
end
def push content
id = content.gsub(/\A.*"_id": *"([^"]*).*\Z/m, '\1')
doc = id && `curl -s #{File.join ENV['ROUCH_URL'], id}`
rev = doc && doc.match('"_rev":') && doc.gsub(/\A.*"_rev": *"([^"]*).*\Z/m, '\1')
rev && content.gsub!(/"_id":/m, '"_rev": "' + rev + '", "_id":')
file = Tempfile.new('app.json')
begin
file << content
file.rewind
puts `curl -s -XPOST #{ENV['ROUCH_URL']} -d@'#{file.path}' -H 'Content-Type: application/json'`
ensure
file.close!
end
end
OptionParser.new do |opts|
opts.banner = "Usage: #{__FILE__} FILENAME [options]"
opts.on("-d", "--database URL", "URL of database") do |v|
ENV['ROUCH_URL'] = v
end
opts.on("-c", "--[no-]combine", "Combine javascripts") do |v|
ENV['ROUCH_COMBINE'] = v.to_s
end
opts.on("-u", "--[no-]uglify", "Uglify source") do |v|
ENV['ROUCH_UGLIFY'] = v.to_s
end
end.parse!
app = strip compile ARGF.filename
ENV['ROUCH_URL'] ? push(app) : puts(app)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment