Skip to content

Commit

Permalink
Fix ActiveModel::Conversion._to_partial_path not using a model's mode…
Browse files Browse the repository at this point in the history
…l_name.

The current implementation of _to_partial_path composes the part of two bits, `collection' and `element'.
ActiveModel::Name also contains these fields, and they are derived the same way _to_partial_path does it.
However, _to_partial_path doesn't use the information in model_name, and solely relies on its own computations instead.
This works for all standard cases, but not necessarily for models that provide a non-standard model_name.

This commit fixes that and has _to_partial_path use model_name if the class responds to it.
  • Loading branch information
RuhmUndAnsehen committed Aug 28, 2023
1 parent 0d46f69 commit 3a3951a
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 1 deletion.
4 changes: 3 additions & 1 deletion activemodel/lib/active_model/conversion.rb
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,9 @@ module ClassMethods # :nodoc:
# Provide a class level cache for #to_partial_path. This is an
# internal method and should not be accessed directly.
def _to_partial_path # :nodoc:
@_to_partial_path ||= begin
@_to_partial_path ||= if respond_to?(:model_name)
"#{model_name.collection}/#{model_name.element}"
else
element = ActiveSupport::Inflector.underscore(ActiveSupport::Inflector.demodulize(name))
collection = ActiveSupport::Inflector.tableize(name)
"#{collection}/#{element}"
Expand Down
4 changes: 4 additions & 0 deletions activemodel/test/cases/conversion_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,10 @@ def persisted?
assert_equal "helicopter/comanches/comanche", Helicopter::Comanche.new.to_partial_path
end

test "to_partial_path handles non-standard model_name" do
assert_equal "attack_helicopters/ah-64", Helicopter::Apache.new.to_partial_path
end

test "#to_param_delimiter allows redefining the delimiter used in #to_param" do
old_delimiter = Contact.param_delimiter
Contact.param_delimiter = "_"
Expand Down
13 changes: 13 additions & 0 deletions activemodel/test/models/helicopter.rb
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,16 @@ class Helicopter
class Helicopter::Comanche
include ActiveModel::Conversion
end

class Helicopter::Apache
include ActiveModel::Conversion

class << self
def model_name
@model_name ||= ActiveModel::Name.new(self).tap do |model_name|
model_name.collection = "attack_helicopters"
model_name.element = "ah-64"
end
end
end
end

0 comments on commit 3a3951a

Please sign in to comment.