Skip to content

Instantly share code, notes, and snippets.

@joshmn
Created August 11, 2015 17:41
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 joshmn/ea3bfd5d7014a2addba3 to your computer and use it in GitHub Desktop.
Save joshmn/ea3bfd5d7014a2addba3 to your computer and use it in GitHub Desktop.
# 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
Copy link
Author

joshmn 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