Method: Praxis::ResourceDefinition::ClassMethods#parent

Defined in:
lib/praxis/resource_definition.rb

#parent(parent = nil, **mapping) ⇒ Object



102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
# File 'lib/praxis/resource_definition.rb', line 102

def parent(parent=nil, **mapping)
  return @parent if parent.nil?

  @routing_prefix = nil # reset routing_prefix

  parent_action = parent.canonical_path
  parent_route = parent_action.primary_route.path

  # if a mapping is passed, it *must* resolve any param name conflicts
  unless mapping.any?
    # assume last capture is the relevant one to replace
    # if not... then I quit.
    parent_param_name = parent_route.names.last

    # more assumptions about names
    parent_name = parent.name.demodulize.underscore.singularize

    # put it together to find what we should call this new param
    param = "#{parent_name}_#{parent_param_name}".to_sym
    mapping[parent_param_name.to_sym] = param
  end

  # complete the mapping and massage the route
  parent_route.names.collect(&:to_sym).each do |name|
    if mapping.key?(name)
      param = mapping[name]
      # FIXME: this won't handle URI Template type paths, ie '/{parent_id}'
      prefixed_path = parent_action.primary_route.prefixed_path
      @parent_prefix = prefixed_path.gsub(/(:)(#{name})(\W+|$)/, "\\1#{param.to_s}\\3")
    else
      mapping[name] = name
    end
  end

  self.on_finalize do
    self.inherit_params_from_parent(parent_action, **mapping)
  end

  @parent = parent
end