Skip to content

Instantly share code, notes, and snippets.

@foca
Created August 5, 2008 04:35
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 foca/4027 to your computer and use it in GitHub Desktop.
Save foca/4027 to your computer and use it in GitHub Desktop.
module Sinatra
class EventContext
def params
@params ||= ParamsParser.new(@route_params.merge(@request.params)).to_hash
end
private
class ParamsParser
attr_reader :hash
def initialize(hash)
@hash = nested(hash)
p @hash
end
alias :to_hash :hash
protected
def nested(hash)
hash.inject(indifferent_hash) do |par, (key,val)|
if key =~ /([^\[]+)\[([^\]]+)\](.*)/
par[$1] ||= indifferent_hash
par[$1].update(nested("#{$2}#{$3}" => val))
elsif key =~ /([^\[]+)\[\](.*)/
par[$1] ||= []
par[$1] << ($2 == "" ? val : nested($2 => val))
else
par[key] = val
end
par
end
end
def indifferent_hash
Hash.new {|h,k| h[k.to_s] if Symbol === k}
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment