Skip to content

Instantly share code, notes, and snippets.

@hirakuro
Created August 17, 2010 08:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hirakuro/528882 to your computer and use it in GitHub Desktop.
Save hirakuro/528882 to your computer and use it in GitHub Desktop.
#!/usr/bin/ruby
require "rubygems"
require "sinatra"
require "haml"
helpers do
def xhr(domain, id, api_suffix=nil)
api_suffix = "_#{api_suffix}" if api_suffix
<<EOT
//// XHR for #{domain} #{id} ////
var xhr_#{id} = new XMLHttpRequest();
xhr_#{id}.onreadystatechange = function(){
//alert(xhr_#{id}.readyState);
if(xhr_#{id}.readyState === 4){
var n = document.getElementById("#{id}");
n.textContent = xhr_#{id}.responseText;
}
}
xhr_#{id}.open("GET", "http://#{domain}:#{request.port}/api#{api_suffix}", true);
xhr_#{id}.send();
EOT
end
def js
<<EOT
function test(){
#{xhr("localhost", "container_local")}
#{xhr("127.0.0.1", "container_127")}
#{xhr("127.0.0.1", "container_127_acao", "with_acao")}
}
window.onload=test;
EOT
end
def puts_log
puts "GET #{request.path}"
puts "Host: #{request.host}"
end
end
get "/" do
haml <<EOT
%html
%head
%title Test
%script{:language=>"javascript", :src=>"http://localhost:#{request.port}/js"}
%body
%h1 LOCALHOST
%p{:id=>"container_local"} DUMMY
%h1 127.0.0.1
%p{:id=>"container_127"} DUMMY
%h1 127.0.0.1 with ACAO
%p{:id=>"container_127_acao"} DUMMY
EOT
end
get "/js" do
js
end
get "/api" do
puts_log
<<EOT
Welcome to API! / #{request.url}
EOT
end
get "/api_with_acao" do
puts_log
response["Access-Control-Allow-Origin"] = "*"
<<EOT
Welcome to API with Access-Control-Allow-Origin! / #{request.url}"
EOT
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment