Skip to content

Instantly share code, notes, and snippets.

$ type rvm | head -n1
rvm is a function
$ screen
(now inside a fresh screen)
$ type rvm | head -n1
rvm is /usr/local/rvm/bin/rvm
@rennex
rennex / gist:2625246
Created May 7, 2012 01:05
Sinatra inline templates test
require "sinatra"
class Foo < Sinatra::Base
end
Foo.inline_templates=nil
p Foo.templates[:thing]
@rennex
rennex / gist:2698224
Created May 15, 2012 00:12
Sinatra env viewer
require "sinatra"
get "/" do
content_type "text/plain"
txt = ""
env.each {|k,v| txt += "\n%30s: %s" % [k,v]}
txt
end
# converts an arbitrary decimal number into a fraction
# returns [input, result, check] where "check" is eval(result) with floats
def frac(str); raise ArgumentError unless str =~ /\A(\d*)\.(\d+)\z/; x=($1+$2).to_i; y=10**($2.size); gcd=x.gcd(y); r="#{x/gcd}/#{y/gcd}"; return [str, r, eval(r+".0")]; end
# testing it with some random examples:
p frac("#{rand 100}.#{rand 10000}")
# => ["39.3575", "15743/400", 39.3575]
# => ["34.7117", "347117/10000", 34.7117]
# => ["41.8720", "5234/125", 41.872]
@rennex
rennex / floatbits.rb
Last active December 20, 2015 18:09
Get the bit representation of a double in Ruby. (pack it as "G" = big-endian double-precision float, unpack as "Q>" = big-endian 64-bit int)
def bits(x) "%064b" % ([x].pack("G").unpack("Q>")[0]) end
bits(0.1)
#=> "0011111110111001100110011001100110011001100110011001100110011010"
bits(-0.1)
#=> "1011111110111001100110011001100110011001100110011001100110011010"
@rennex
rennex / emailtemplate.rb
Created August 11, 2013 03:44
Email template system for constructing plaintext emails (the example shows usage in a Sinatra route, with the mail gem)
class EmailTemplate
def initialize
@io = StringIO.new
end
def puts(*args)
@io.puts *args
end
def print(*args)
@io.print *args
end
@rennex
rennex / simpletabs.html
Last active December 25, 2015 13:39
HTML tabs using a simple piece of standalone JS and some CSS
<html>
<head>
<style type="text/css">
#tabnav {
list-style-type: none;
padding: 0;
}
#tabnav li {
display: inline;
padding: 0.5em;
# constant-time comparison algorithm to prevent timing attacks
# (borrowed from devise)
def secure_compare(a, b)
return false if a.bytesize != b.bytesize
l = a.unpack "C#{a.bytesize}"
res = 0
b.each_byte { |byte| res |= byte ^ l.shift }
res == 0
end
@rennex
rennex / sinatra trailing slash.rb
Last active December 29, 2015 01:39
If a request to my Sinatra app would return 404 just because of a trailing slash, redirect to the correct path.
not_found do
# redirect GET and HEAD requests to "/foo/" to "/foo"
if (request.get? || request.head?) && request.path_info[-1] == "/"
newpath = request.path_info.chop
if Sinatra::Application.routes["GET"].find {|re,*other| newpath =~ re }
redirect to(newpath)
end
end
haml :x404
end
require "sinatra"
DATA = File.read("data.txt")
get "/" do
"I have some data for you: #{DATA}"
end