Just curious what the difference is between these two in a Rails gem:
write_inheritable_attribute(:sample, "sample")
self.sample = "sample"
I couldn’t find any good documentation on write_inheritable_attribute, and was just reading through some gem source and found the former used a few times. Thanks!
For a simple class or module, there wouldn’t be a difference, but with more complex modules that may be loaded with multiple other modules, methods like
write_inheritable_attributecan help you modify objects easily and reliably without having to worry about scope, private/protected methods and all kinds of interference from ruby metaprogramming magic likemethod_missing.In short, when you write
foo.sample = "sample"there are all kinds of things that may happen before, after, or instead of setting the attribute, especially if the object uses ActiveModel or an ORM. When you usefoo.write_inheritable_attribute(:sample, "sample")you have much greater control over what happens.