Module: ContentfulRails::NestedResource::ClassMethods
- Defined in:
- lib/contentful_rails/nested_resource.rb
Instance Method Summary collapse
-
#get_nested_from_path_by(field, path, opts = {}) ⇒ Object
Get a deeply-nested object from a string which represents the heirarchy.
Instance Method Details
#get_nested_from_path_by(field, path, opts = {}) ⇒ Object
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
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
# File 'lib/contentful_rails/nested_resource.rb', line 14 def get_nested_from_path_by(field, path, opts = {}) = {delimiter: '/', unescape: false, prefix: ""} .merge!(opts) path = CGI::unescape(path) if [:unescape] delimiter = [:delimiter] prefix = [:prefix].empty? ? "" : "#{delimiter}#{[:prefix]}#{delimiter}" root, *children = "#{prefix}#{path}".gsub(/^\//, '').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? return root_entity.get_child_entity_from_path_by(field, children) elsif root_entity return root_entity else return nil end end |