ANN: attr_immutable plugin

Hiho,

Thought this might of some use to someone out there.

  • John


DESCRIPTION:

attr_immutable is simple plugin for Rails 0.14.3+ which will cause
attributes
flagged as immutable to be just that: immutable. The attributes
flagged will
be rendered frozen on read, and throw an
ImmutableAttributeAssignmentError on
assignment only after the record has been persisted (save/
create) or loaded
(find).

Comments and suggestions welcome.



INSTALLATION:

Download and extract the following into your vendor/plugins
directory.

 http://www.psynix.com/rails/attr_immutable/attr_immutable.tar.gz
 http://www.psynix.com/rails/attr_immutable/attr_immutable.tar.bz2


USAGE:

class User < ActiveRecord
attr_immutable :username # Make username immutable after
save/create
end

me = User.new
me.username = ‘testuser’ => ‘testuser’
me.password = ‘testpassword’ => ‘testpassword’
me.save => true
me.reload
me.username.frozen? => true
me[:username].frozen? => true
me.attributes[‘username’].frozen? => true
me.username = ‘anotherusername’ =>
Plasma::ImmutableAttributeAssignmentError thrown
me[:username] = ‘anotherusername’ =>
Plasma::ImmutableAttributeAssignmentError thrown

This plugin was developed using Rails 0.14.3. It may work on previous
versions. Use at your own risk.


John M. [email protected]

Don’t wanna step on your toes, but one could as well do

class User < ActiveRecord
attr_protected :name
end

Then you as an admin would still have the possibilibty to change the
username through proper controllers.

Your solution might have it’s place though - it’s certainly a cleaner
solution if one never ever wants to change an attribute
(Just wrote this in case you didn’t know about attr_protected)

Cheers :slight_smile:
Rob

Hi,

I’m fully aware of attr_protected … it does however serve a
different purpose ie. that of disabling mass assignment of specified
attributes.

Thanks for the comments anyway :slight_smile:

  • John

On 28/11/2005, at 8:03 PM, Robert wrote:

http://lists.rubyonrails.org/mailman/listinfo/rails

John M. [email protected]