Wednesday, December 28, 2011

Bugging around Active Support's Class.class_attribute extension

by Sandip Ransing 0 comments

We all know Active Support library constantly keeps adding new extensions to ruby core library and hence rails framework.
Do you know now inside ruby class we can have class_attribute placeholder.
class A class_attribute :counter, :access_time end A.counter = 12 A.counter #=> 12 A.new.counter #=> 12
Inheritance class B < A end B.counter #=> 12 B.access_time #=> nil B.access_time = Time.now B.access_time #=> Wed Dec 28 18:55:06 +0530 2011 B.new.access_time #=> Wed Dec 28 18:55:06 +0530 2011 A.access_time = nil
Restricting instance from writing class_attributes
class V class_attribute :counter, :instance_writer => false end V.new.counter = 12 NoMethodError: undefined method `counter=' for #
Other ways
a_class = Class.new{class_atrribute :counter} a_class.counter = 13 a_class.counter #=> 13 a_class.new.counter #=> 13 p = Class.new { class_attribute :help, :instance_writer => false } p.new.help = 'Got a second!' NoMethodError: undefined method `help=' for #<#:0x7f8f9d5b1038> p.help = 'Got a second!' p.help #=> "Got a second!"

blog comments powered by Disqus

About The Author

Sandip is a ruby on rails developer based in pune and also a blogger at funonrails. Opensource contributor and working with Josh software Private Limited. for more info read Follow Sandip on Twitter for updates.

Connect With Me...

Github Projects

@sandipransing Twitter