Created
October 31, 2012 18:18
-
-
Save Flamefork/3988819 to your computer and use it in GitHub Desktop.
Convert php-style nested attribute arrays to rails-style. Dirty hack.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# put this into config/initializers | |
module Rack | |
module Utils | |
def parse_nested_query_with_restkit(qs, d = nil) | |
qs = RestkitConverter.new.convert(qs) if qs[/\[\]/] | |
parse_nested_query_without_restkit(qs, d) | |
end | |
alias_method_chain :parse_nested_query, :restkit | |
module_function :parse_nested_query | |
module_function :parse_nested_query_without_restkit | |
end | |
end | |
class RestkitConverter | |
def convert(s) | |
transform_lines(s.split('&')).join('&') | |
end | |
protected | |
def transform_lines(lines) | |
grouped_lines = lines.group_by { |line| line[/.*?\[\]/] || '' } | |
return lines if grouped_lines.length == 1 | |
grouped_lines.map { |prefix, sublines| | |
sublines = sublines.map { |line| line[prefix.length..-1] } | |
key = sublines.first[/[^=]*/] | |
groups = sublines.inject([]) { |accum, line| | |
accum << [] if line[/[^=]*/] == key | |
accum.last << line | |
accum | |
} | |
groups.map_with_index { |group, i| | |
transform_lines(group).map { |line| | |
prefix.gsub(/\[\]/, "[#{i}]") + line | |
} | |
} | |
}.flatten | |
end | |
end | |
module Enumerable | |
def map_with_index | |
result = [] | |
self.each_with_index do |elt, idx| | |
result << yield(elt, idx) | |
end | |
result | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment