gouf
12/12/2014 - 2:04 PM

tree title (by slash)

tree title (by slash)

require 'pp'

module Categorizer
  def categorize(title_string)
    title = title_string.split('/').reverse
    result = []
    while title.size > 0 do
      x, y = title.shift, title.first
      if x.nil? # parent has nil?
        result << category.new(nil, y)
      else
        result << category.new(y, x)
      end
    end
    result.reverse
  end

  def category
    name = 'Category'
    if Struct::const_defined?(name)
      Struct.const_get(name)
    else
      Struct.new(name, :parent, :me)
    end
  end
end

include Categorizer

title_a = '2014/12/24/daily_report/my_name'
title_b = '2014/12/schedule/01/my_name'

pp categorize(title_a)
puts ''
pp categorize(title_b)

# =>
# [#<struct Struct::Category parent=nil, me="2014">,
#  #<struct Struct::Category parent="2014", me="12">,
#  #<struct Struct::Category parent="12", me="24">,
#  #<struct Struct::Category parent="24", me="daily_report">,
#  #<struct Struct::Category parent="daily_report", me="my_name">]
#
# [#<struct Struct::Category parent=nil, me="2014">,
#  #<struct Struct::Category parent="2014", me="12">,
#  #<struct Struct::Category parent="12", me="schedule">,
#  #<struct Struct::Category parent="schedule", me="01">,
#  #<struct Struct::Category parent="01", me="my_name">]