Skip to content

Commit

Permalink
Improve docs and code.
Browse files Browse the repository at this point in the history
  • Loading branch information
josevalim committed Aug 23, 2011
1 parent 117bed8 commit 18189d0
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 22 deletions.
1 change: 1 addition & 0 deletions lib/inherited_resources/class_methods.rb
Expand Up @@ -279,6 +279,7 @@ def acts_as_polymorphic! #:nodoc:
end

def acts_as_shallow! #:nodoc:
include BelongsToHelpers
include ShallowHelpers
end

Expand Down
47 changes: 25 additions & 22 deletions lib/inherited_resources/shallow_helpers.rb
@@ -1,40 +1,43 @@
module InheritedResources
# Shallow provides a functionality that goes on pair with Rails' shallow.
# It is very similar to "optional" but it actually finds all the parents
# resources instead of leaving them blank. Consider the following example:
#
# belongs_to :post, :shallow => true do
# belongs_to :comment
# end
#
# When accessed as /comments/1, Inherited Resources will automatically get
# the post resource so both objects are actually accessible through the views.
#
# However, when using optional, Inherited Resources wouldn't actually bother
# with finding the parent object.
module ShallowHelpers
include BelongsToHelpers

private

# Evaluate the parent given. This is used to nest parents in the
# association chain.
#

# Maps parents_symbols to build association chain. In this case, it
# simply return the parent_symbols, however on polymorphic belongs to,
# it has some customization.
#
def symbols_for_association_chain #:nodoc:
parent_symbols = parents_symbols.dup
if parents_symbols.size > 1 && !params[:id]
inst_class_name = parent_symbols.pop
finder_method = resources_configuration[inst_class_name][:finder] || :find
instance = resources_configuration[inst_class_name][:parent_class].send(finder_method, params[resources_configuration[inst_class_name][:param]])
load_parents(instance, parent_symbols)
end
if params[:id]
instance = nil

if id = params[:id]
finder_method = resources_configuration[:self][:finder] || :find
instance = self.resource_class.send(finder_method, params[:id])
load_parents(instance, parent_symbols)
instance = self.resource_class.send(finder_method, id)
elsif parents_symbols.size > 1
config = resources_configuration[parent_symbols.pop]
finder_method = config[:finder] || :find
instance = config[:parent_class].send(finder_method, params[config[:param]])
end

load_parents(instance, parent_symbols) if instance
parents_symbols
end

def load_parents(instance, parent_symbols)

parent_symbols.reverse.each do |parent|
instance = instance.send(parent)
params[resources_configuration[parent][:param]] = instance.to_param
config = resources_configuration[parent]
params[config[:param]] = instance.to_param
end
end
end

end

0 comments on commit 18189d0

Please sign in to comment.