Skip to content

Instantly share code, notes, and snippets.

@nsmmrs
Last active April 22, 2023 04:23
Show Gist options
  • Save nsmmrs/de6e8499eb5e228048222ee167ae043a to your computer and use it in GitHub Desktop.
Save nsmmrs/de6e8499eb5e228048222ee167ae043a to your computer and use it in GitHub Desktop.
Hash#breadcrumbs
class Hash
def self.breadcrumbs(hash)
hash.flat_map do |k,v|
if v.is_a?(Hash)
breadcrumbs(v).map{|p| [k, *p]}
else
[k]
end
end
end
def breadcrumbs(**options)
@_all_trails ||= begin
base = self.class.breadcrumbs(self)
fragments = base.flat_map{|p| p.map.with_index(1){|_,i| p.slice(0,i) } }
(base + fragments).uniq
end
trails = @_all_trails
if options.has_key?(:ending_in)
tail = options[:ending_in]
tail = [tail] unless tail.is_a? Array
trails = trails.select{|p| p.slice((- tail.length)..-1) == tail }
end
if options[:with_values] == true
trails.map{|p| [p, dig(*p)] }.to_h
else
trails
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment