Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix has_many_nested for models in modules #125

Closed
wants to merge 2 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 8 additions & 4 deletions lib/contentful_model/associations/has_many_nested.rb
Original file line number Diff line number Diff line change
Expand Up @@ -25,23 +25,23 @@ module ClassMethods
# to write your own recursion for this, because it's probably an implementation-specific problem.
# rubocop:disable Style/PredicateName
def has_many_nested(association_name, options = {})
has_many association_name, class_name: to_s, inverse_of: :"parent_#{to_s.underscore}"
belongs_to_many :"parent_#{to_s.underscore.pluralize}", class_name: to_s
has_many association_name, class_name: to_s, inverse_of: :"parent_#{has_many_nested_name}"
belongs_to_many :"parent_#{has_many_nested_name.pluralize}", class_name: to_s
root_method = options[:root] if options[:root].is_a?(Proc)

# If there's a root method defined, set up a class method called root_[class name]. In our example this would be
# Page.root_page.
# @return [Object] the root entity returned from the proc defined in has_many_nested
if defined?(root_method) && root_method.is_a?(Proc)
# @return [Object] the root entity
define_method :"root_#{to_s.underscore}" do
define_method :"root_#{has_many_nested_name}" do
root_method.call
end
end

# A utility method which returns the parent object; saves passing around interpolated strings
define_method :parent do
parents = send(:"parent_#{self.class.to_s.underscore.pluralize}")
parents = send(:"parent_#{self.class.has_many_nested_name.pluralize}")
parents.first unless parents.nil?
end

Expand Down Expand Up @@ -132,6 +132,10 @@ def has_many_nested(association_name, options = {})
send(:private, :flatten_hash)
end
# rubocop:enable Style/PredicateName

def has_many_nested_name
to_s.demodulize.underscore
end
end
end
end
Expand Down