module ContentfulRails::NestedResource::ClassMethods
Class methods for NestedResource
Public Instance Methods
get_nested_from_path_by(field, path, opts = {})
click to toggle source
Get a deeply-nested object from a string which represents the heirarchy. The obvious use for this is to find an object from a URL e.g. /grandparent/parent/child
@param field [Symbol] the field to search by - for example, :slug @param path [String] the path as a forward-slash separated string
# File lib/contentful_rails/nested_resource.rb, line 16 def get_nested_from_path_by(field, path, opts = {}) options = { delimiter: '/', unescape: false, prefix: '' } options.merge!(opts) path = CGI::unescape(path) if options[:unescape] delimiter = options[:delimiter] prefix = options[:prefix].empty? ? '' : "#{delimiter}#{options[:prefix]}#{delimiter}" root, *children = "#{prefix}#{path}".gsub(%r{/^\//}, '').split(delimiter) if field.to_sym == :id # we need to call find() to get by ID root_entity = find(root) else begin root_entity = search(field => root).first rescue Contentful::BadRequest # we have something which needs find_by called on it root_entity = find_by(field => root).first end end if root_entity && root_entity.has_children? root_entity.get_child_entity_from_path_by(field, children) elsif root_entity root_entity end end