Module: ContentfulRails::NestedResource

Defined in:
lib/contentful_rails/nested_resource.rb

Defined Under Namespace

Modules: ClassMethods

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(base) ⇒ Object



4
5
6
# File 'lib/contentful_rails/nested_resource.rb', line 4

def self.included(base)
  base.extend ClassMethods
end

Instance Method Details

#get_child_entity_from_path_by(field, children) ⇒ Object

Given a field and an array of child fields, we need to recurse through them to get the last one

Parameters:

  • the (Symbol)

    field we need to search for

  • an (Array)

    array of field values to match against

Returns:

  • an entity matching this class, which is the last in the tree



50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/contentful_rails/nested_resource.rb', line 50

def get_child_entity_from_path_by(field, children)
  # the next child in the path
  child_value = children.shift
  # get the child entity
  child = self.send(:children).find {|child| child.send(field) == child_value}
  if child && children.size > 0
    # we have some recursion to do - we're not at the end of the array
    # so call this method again with a smaller set of children
    child.get_child_entity_from_path_by(field, children)
  else
    return child #this is the final thing in the array - return it
  end
end

#nested_path_by(field, opts = {}) ⇒ String

Given a field (and optional delimiter), return a path to the current object. e.g. you’d end up with /path/to/page (where this object is ‘page’)

Parameters:

  • the (Symbol)

    field to use to create the path

  • the (String)

    delimiter to use. Defaults to “/”

Returns:

  • (String)

    the path as a string



69
70
71
72
73
74
75
76
# File 'lib/contentful_rails/nested_resource.rb', line 69

def nested_path_by(field, opts = {})
  options = {delimiter: "/", prefix: ""}
  options.merge!(opts)
  delimiter = options[:delimiter]
  prefix = options[:prefix].empty? ? "" : "#{options[:prefix]}#{delimiter}"
  path = ([self] + ancestors).reverse.collect {|a| a.send(field)}.join(delimiter).gsub(prefix,"")
  return delimiter + path
end