@@ -6,7 +6,36 @@ class Model
66 include ActiveModel ::Serializers ::JSON
77 include ActiveModel ::Model
88
9- class_attribute :attribute_names
9+ # Configuration to avoid a breaking change with older versions of this class which lacked defined attributes.
10+ # Previous behavior was: 1) initialized attributes were the
11+ class_attribute :attributes_are_always_the_initialization_data , instance_writer : false , instance_reader : false
12+ self . attributes_are_always_the_initialization_data = true
13+ module AttributesAreAlwaysTheInitializationData
14+ def initialize ( attributes = { } )
15+ @initialized_attributes = attributes && attributes . symbolize_keys
16+ super
17+ end
18+
19+ # Defaults to the downcased model name.
20+ def id
21+ @initialized_attributes . fetch ( :id ) { self . class . model_name . name && self . class . model_name . name . downcase }
22+ end
23+
24+ def attributes
25+ @initialized_attributes
26+ end
27+ end
28+
29+ def self . inherited ( subclass )
30+ if subclass . attributes_are_always_the_initialization_data
31+ unless subclass . included_modules . include? ( AttributesAreAlwaysTheInitializationData )
32+ subclass . prepend ( AttributesAreAlwaysTheInitializationData )
33+ end
34+ end
35+ super
36+ end
37+
38+ class_attribute :attribute_names , instance_writer : false , instance_reader : false
1039 # Initialize +attribute_names+ for all subclasses. The array is usually
1140 # mutated in the +attributes+ method, but can be set directly, as well.
1241 self . attribute_names = [ ]
@@ -37,7 +66,7 @@ def initialize(attributes = {})
3766 # +attributes+ are returned frozen to prevent any expectations that mutation affects
3867 # the actual values in the model.
3968 def attributes
40- attribute_names . each_with_object ( { } ) do |attribute_name , result |
69+ self . class . attribute_names . each_with_object ( { } ) do |attribute_name , result |
4170 result [ attribute_name ] = public_send ( attribute_name ) . freeze
4271 end . with_indifferent_access . freeze
4372 end
0 commit comments