Skip to content

Instantly share code, notes, and snippets.

@erlingwl
Forked from pkordel/gist:5386788
Last active December 16, 2015 05:49
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 erlingwl/5386985 to your computer and use it in GitHub Desktop.
Save erlingwl/5386985 to your computer and use it in GitHub Desktop.
# -*- encoding : utf-8 -*-
require 'unit_spec_helper'
require 'ostruct'
describe "Parser" do
let(:expected) {
[
["(0) Mammal", 1],
["(0) Mammal | (0) Dog", 3],
["(0) Mammal | (0) Dog | (0) Dobey", 6],
["(0) Mammal | (0) Dog | (1) Beagle", 5],
["(0) Mammal | (1) Cow", 4],
["(0) Mammal | (2) Cat", 2]
]
}
it "should work" do
build_it_from(test_hash).should == expected
end
end
def build_it_from(hash, string = nil)
array = []
hash.each do |struct, child_hash|
array << [format_string(string, struct), struct.id]
array.concat(build_it_from(child_hash, format_string(string, struct))) if child_hash.size > 0
end
array
end
def format_string(string, struct)
[string, "(#{struct.pos_level}) #{struct.title}"].compact.join(" | ")
end
def test_hash
{
OpenStruct.new(id: 1, title: "Mammal", pos_level: 0) => {
OpenStruct.new(id: 3, title: "Dog", pos_level: 0) => {
OpenStruct.new(id: 6, title: "Dobey", pos_level: 0) => {},
OpenStruct.new(id: 5, title: "Beagle", pos_level: 1) => {}
},
OpenStruct.new(id: 4, title: "Cow", pos_level: 1) => {},
OpenStruct.new(id: 2, title: "Cat", pos_level: 2) => {}
}
}
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment