lib/aston.rb in aston-0.2.1 vs lib/aston.rb in aston-0.2.2
- old
+ new
@@ -12,10 +12,14 @@
def initialize(data = {})
@data = data
end
+ def to_hash
+ @data
+ end
+
def [](key)
@data[key]
end
def []=(key, value)
@@ -89,11 +93,11 @@
def []=(key, value)
@attributes[key] = value
end
def <<(value)
- @content << value
+ tap { @content << value }
end
def ==(other)
other.is_a?(Aston) && @name == other.name && @attributes == other.attributes && @content == other.content
end
@@ -102,11 +106,24 @@
comment = "<!-- Aston:#{__id__}:#{name} -->"
opening = @attributes.data.empty? ? "<#{name}>" : ["<#{name}", *@attributes].join(' ') << '>'
[comment, opening, *@content, "</#{name}>"].join("\n")
end
+ def to_hash(remove_empty: false)
+ {
+ name: @name,
+ attributes: @attributes.to_hash,
+ content: @content.data.map { |e| e.is_a?(Aston) ? e.to_hash(remove_empty: remove_empty) : e }
+ }.tap do |hash|
+ if remove_empty
+ hash.delete(:attributes) if hash[:attributes] == {}
+ hash.delete(:content) if hash[:content] == []
+ end
+ end
+ end
+
def to_json(opts = nil)
- { name: @name, attributes: @attributes, content: @content }.to_json(opts)
+ to_hash.to_json(opts)
end
def self.parse_hash(hash)
name = hash.fetch('name', hash.fetch(:name, ''))
attributes = hash.fetch('attributes', hash.fetch(:attributes, {}))