Skip to content

Instantly share code, notes, and snippets.

@cainlevy
Created April 30, 2018 22:05
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cainlevy/5318510f91b26bb65bf64bd9315690af to your computer and use it in GitHub Desktop.
Save cainlevy/5318510f91b26bb65bf64bd9315690af to your computer and use it in GitHub Desktop.
parsing mobiledoc in ruby
require 'keyword_struct'
Mobiledoc = KeywordStruct.new(:version, :markups, :atoms, :cards, :sections) do
Markup = Struct.new(:tag, :attrs)
Atom = Struct.new(:name, :text, :payload)
Card = Struct.new(:name, :payload)
# Parses a serialized Mobiledoc into a collection of Ruby objects
def self.parse(str)
json = JSON.parse(str)
new(
version: json['version'],
markups: Array(json['markups']).map do |(tag, attrs)|
Markup.new(tag, attrs.in_groups_of(2).to_h)
end,
atoms: Array(json['atoms']).map do |a|
Atom.new(*a)
end,
cards: Array(json['cards']).map do |c|
Card.new(*c)
end,
sections: json['sections'] # TODO
)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment