Hi Nick, On Fri, Jan 21, 2011 at 12:41 PM, Nick Sutterer <apoton...@gmail.com> wrote: > According to the docs, class_attribute does implement inheritance for > class instance variables. However, it doesn't work as it is intended > to, at least if you use "mutual structures", like Hash. > > Base.foo = {} > Subclass.foo[:bar] = "bar" > > Base.foo # => {:bar => "bar"} > > I'm sorry, but this is WRONG and dangerous. The docs tell me to "use > setters" here - not sure how this is supposed to work. > > Another "solution" is to initialize the ivar in the subclass, again, > as done here: https://github.com/rails/rails/commit/09195f10bd3 > > SO, if I need to initialize the ivar, I don't need inheritance. Why is > that called "inheritance" at all? > > By accident I solved this with a 10-liner months ago, why not use > something like that? > https://github.com/apotonick/hooks/blob/master/lib/hooks/inheritable_attribute.rb > > It's simple, clean and does exactly what you expect. > > > I just found out class_attribute nearly broke my code, so all I want > is prevent people from stepping into that trap, too :-D > > Cheers!
# To modify an inherited hash in-place, each subclass needs its own copy up-front. Use class_inheritable_attribute for this copy-on-inherit behavior. class Base class_inheritable_attribute :options self.options = {} end class Subclass < Base self.options[:foo] = 'bar' end # Use class_attribute for inheritance that behaves just like Ruby methods. The superclass value is used unless it's overridden by a subclass' value. class Base class_attribute :options self.options = {} end class Subclass < Base self.options = self.options.merge(:foo => 'bar') end # With a declarative API class Base class_attribute :options def self.config(options) self.options = (self.options || {}).merge(options) end end class Subclass < Base config :foo => 'bar' end Jeremy -- You received this message because you are subscribed to the Google Groups "Ruby on Rails: Core" group. To post to this group, send email to rubyonrails-core@googlegroups.com. To unsubscribe from this group, send email to rubyonrails-core+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/rubyonrails-core?hl=en.