@@ -120,7 +120,7 @@ def remove_associated_in_to(doc, inverse)
120
120
# @param [ Object ] id The id of the bound document.
121
121
def bind_foreign_key ( keyed , id )
122
122
unless keyed . frozen?
123
- keyed . you_must ( _association . foreign_key_setter , id )
123
+ try_method ( keyed , _association . foreign_key_setter , id )
124
124
end
125
125
end
126
126
@@ -135,8 +135,8 @@ def bind_foreign_key(keyed, id)
135
135
# @param [ Document ] typed The document that stores the type field.
136
136
# @param [ String ] name The name of the model.
137
137
def bind_polymorphic_type ( typed , name )
138
- if _association . type
139
- typed . you_must ( _association . type_setter , name )
138
+ if _association . type && ! typed . frozen?
139
+ try_method ( typed , _association . type_setter , name )
140
140
end
141
141
end
142
142
@@ -151,8 +151,8 @@ def bind_polymorphic_type(typed, name)
151
151
# @param [ Document ] typed The document that stores the type field.
152
152
# @param [ String ] name The name of the model.
153
153
def bind_polymorphic_inverse_type ( typed , name )
154
- if _association . inverse_type
155
- typed . you_must ( _association . inverse_type_setter , name )
154
+ if _association . inverse_type && ! typed . frozen?
155
+ try_method ( typed , _association . inverse_type_setter , name )
156
156
end
157
157
end
158
158
@@ -167,8 +167,8 @@ def bind_polymorphic_inverse_type(typed, name)
167
167
# @param [ Document ] doc The base document.
168
168
# @param [ Document ] inverse The inverse document.
169
169
def bind_inverse ( doc , inverse )
170
- if doc . respond_to? ( _association . inverse_setter )
171
- doc . you_must ( _association . inverse_setter , inverse )
170
+ if doc . respond_to? ( _association . inverse_setter ) && ! doc . frozen?
171
+ try_method ( doc , _association . inverse_setter , inverse )
172
172
end
173
173
end
174
174
@@ -223,6 +223,24 @@ def unbind_from_relational_parent(doc)
223
223
bind_polymorphic_type ( doc , nil )
224
224
bind_inverse ( doc , nil )
225
225
end
226
+
227
+ # Convenience method to perform +#try+ but return
228
+ # nil if the method argument is nil.
229
+ #
230
+ # @example Call method if it exists.
231
+ # object.try_method(:use, "The Force")
232
+ #
233
+ # @example Return nil if method argument is nil.
234
+ # object.try_method(nil, "The Force") #=> nil
235
+ #
236
+ # @param [ String | Symbol ] method_name The method name.
237
+ # @param [ Object... ] *args The arguments.
238
+ #
239
+ # @return [ Object | nil ] The result of the try or nil if the
240
+ # method does not exist.
241
+ def try_method ( object , method_name , *args )
242
+ object . try ( method_name , *args ) if method_name
243
+ end
226
244
end
227
245
end
228
246
end
0 commit comments