Skip to content

Loading…

Naming helpers should first check if passed object responds to model_name #7293

Merged
merged 1 commit into from

3 participants

@Bertg

Hi,

I refactored a piece of the ActiveModel::Naming module. In the part of the code that tries to find the model_name for the passed argument, I changed the implementation from "type based" (checking for Class) to "behavior based" (checking for method)

This change behaves almost 100% the same as the previous implementation.

  • Makes the same assumptions as old code. If argument responds to to_model, then .to_model.class.model_name can be called.
  • If argument it is not a Class, call .class.model_name
  • This version however allows the argument to directly respond to model_name if it can.

This gives a (very minor) speed boost if a class is passed, but more importantly; it allows an instance to define its "name".

We use one class to store most of our data. However, how this class should behave, depends on it's configuration. Routing, human names, partials all depend on this configuration. By allowing the instance to respond to model_name, we can easily take advantage of all ActiveModel based code.

@steveklabnik
Ruby on Rails member

Anything that removes is_a? is a 100% :+1: :metal: from me.

@tenderlove tenderlove merged commit 2da242f into rails:master
@Bertg

Alright, that was fast. Thx!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Showing with 3 additions and 5 deletions.
  1. +3 −5 activemodel/lib/active_model/naming.rb
View
8 activemodel/lib/active_model/naming.rb
@@ -300,11 +300,9 @@ def self.param_key(record_or_class)
private
def self.model_name_from_record_or_class(record_or_class)
- (record_or_class.is_a?(Class) ? record_or_class : convert_to_model(record_or_class).class).model_name
- end
-
- def self.convert_to_model(object)
- object.respond_to?(:to_model) ? object.to_model : object
+ return record_or_class.model_name if record_or_class.respond_to?(:model_name)
+ return record_or_class.to_model.class.model_name if record_or_class.respond_to?(:to_model)
+ record_or_class.class.model_name
end
end
Something went wrong with that request. Please try again.