Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
# hack of the year
require 'json'
class String
def string_between_markers marker1, marker2
self[/#{Regexp.escape(marker1)}(.*?)#{Regexp.escape(marker2)}/m, 1]
end
end
file = File.read('schema.rb')
content = file.split(' do', 2)[1].rpartition('end')[0]
json = []
file.split(/^\n/).each do |schema_section|
parts = schema_section.split("\n")
if parts[0].strip[0, 12] == 'create_table'
model = parts[0].string_between_markers('"', '"')
attribs = []
parts.shift; parts.pop
parts.each do |col|
col.gsub!("t.", '{')
s = col.split(" ", 2).join(':')
hsh = eval("#{s}}")
hsh[:type] = hsh.keys[0]
hsh[:name] = hsh.values[0]
hsh.delete(hsh.keys[0])
attribs << hsh
end
json << {:model => model, :attributes => attribs}
end
end
puts json.to_json
@joshmn

This comment has been minimized.

Copy link
Owner Author

commented Aug 11, 2015

require 'json'
class String
  def string_between_markers marker1, marker2
    self[/#{Regexp.escape(marker1)}(.*?)#{Regexp.escape(marker2)}/m, 1]
  end
end

file = File.read('schema.rb')
content = file.split(' do', 2)[1].rpartition('end')[0]
json = [] 
file.split(/^\n/).each do |schema_section|
    parts = schema_section.split("\n")
    if parts[0].strip[0, 12] == 'create_table'
        model = parts[0].string_between_markers('"', '"')
        attribs = [] 
        required = []
        parts.shift; parts.pop 
        parts.each do |col|
            col.gsub!("t.", '{')
            s = col.split(" ", 2).join(':')
            hsh = eval("#{s}}")

            hsh[:type] = hsh.keys[0]
            hsh[:title] = hsh.values[0]
            hsh.delete(hsh.keys[0])
            if !hsh[:null].nil?
                required << hsh[:title]
            end

            attribs << hsh 
        end

        hash = {:model => model, :properties => attribs}
        hash[:required] = required if required.count > 0 
        json << hash
    end
end

puts json.to_json
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.