[Rails] Freezing Variable Assignment

Eric Hodel drbrain at segment7.net
Mon Dec 6 17:21:08 GMT 2004


On 05 Dec 2004, at 18:51, Nicholas Van Weerdenburg wrote:

> Hi,
>
> Is there a feature to freeze variable assignment?
>
> e.g.
> a="hello"
> a.assignfreeze
> a="goodbye"  # ===> generates exception

No.  All variables in Ruby are references.  You could do this via a 
proxy object, but that probably wouldn't work well in this case.

> Or, in a related vein, a type freeze, so that only similar objects can 
> be added.

You could do this with a subclass of the container, but then you lose 
the beauty of Duck Typing brought to you by Ruby's dynamic typing.

> I realize that constants offer assignment freezing to a certain degree.

Any object can be frozen, which prevents modification to it, but not to 
its contained objects:

$ ruby
a = ['foo']
a.freeze
a[0] << ' bar'
a << 'baz'
-:4:in `<<': can't modify frozen array (TypeError)
         from -:4

> The reason I ask, is that I stepped over-top of some framework
> variables today, and it was hard to find out what was going on.

The best answer is to be more careful, because nobody likes to shoot 
themselves in the foot.

> Where as ruby protects keywords, it would be nice if frameworks or 
> custom
> domain specific languages could do the same.

My (personal) best advice is to get cozy with unit testing.  You can 
flush out these kinds of problems more reliably than learning a domain 
specific language and the framework you're using.  The DSL will still 
give you ample opportunity for foot-shooting.

Plus you get automatic protection from foot-shooting as your test 
library grows. You've already covered all the places you shot yourself 
in the past, preventing their reoccurrence.



More information about the Rails mailing list