ActiveRecord attribute= overload

I want to overload the = operator for one of the attributes in a model
to run a filter on the input. However I can’t do this:

def attribute=(data)
self.attribute = filter(data)
end

because that creates an infinite recursive loop.

How do I get around this?

this should work (did not check):

class Bla < ActiveRecord:Base
alias :old_attribute :attribute

def attribute=(data)
self.old_attribute = filter(data)
end

end

-------- Original-Nachricht --------
Datum: Tue, 13 Jun 2006 13:05:12 +0200
Von: ryan [email protected]
An: [email protected]
Betreff: [Rails] ActiveRecord attribute= overload

now I did check:

class Bla < ActiveRecord:Base
alias :old_attribute= :attribute=

def attribute=(data)
self.old_attribute = filter(data)
end

end

-------- Original-Nachricht --------
Datum: Tue, 13 Jun 2006 13:08:06 +0200
Von: Peter E. [email protected]
An: [email protected]
Betreff: Re: [Rails] ActiveRecord attribute= overload

Now I get.

NameError (undefined method attribute=' for class Bla’):

I know that I have a field called ‘attribute’ in the correct table.
Shouldn’t there be a method called attribute= to overload?

Peter E. wrote:

now I did check:

class Bla < ActiveRecord:Base
alias :old_attribute= :attribute=

def attribute=(data)
self.old_attribute = filter(data)
end

end

-------- Original-Nachricht --------
Datum: Tue, 13 Jun 2006 13:08:06 +0200
Von: Peter E. [email protected]
An: [email protected]
Betreff: Re: [Rails] ActiveRecord attribute= overload

I expected ‘attribute’ to be a placeholder for some attribute from
you…

like:

class Address < ActiveRecord:Base
alias :old_name= :name=

def name=(value)
self.old_name = name.capitalize
end
end

-------- Original-Nachricht --------
Datum: Tue, 13 Jun 2006 13:25:03 +0200
Von: ryan [email protected]
An: [email protected]
Betreff: [Rails] Re: Re: ActiveRecord attribute= overload

Sorry I wasn’t clear. I guess I didn’t understand how ActiveRecord
handled the attributes.

The example from Sam works well.

Peter E. wrote:

I expected ‘attribute’ to be a placeholder for some attribute from
you…

like:

class Address < ActiveRecord:Base
alias :old_name= :name=

def name=(value)
self.old_name = name.capitalize
end
end

-------- Original-Nachricht --------
Datum: Tue, 13 Jun 2006 13:25:03 +0200
Von: ryan [email protected]
An: [email protected]
Betreff: [Rails] Re: Re: ActiveRecord attribute= overload

def attribute=(data)
write_attribute(:attribute, filter(data))
end

-Sam

ryan wrote:

Sorry I wasn’t clear. I guess I didn’t understand how ActiveRecord
handled the attributes.

The example from Sam works well.

Peter E. wrote:

I expected ‘attribute’ to be a placeholder for some attribute from
you…

like:

class Address < ActiveRecord:Base
alias :old_name= :name=

def name=(value)
self.old_name = name.capitalize
end
end

I believe you can also use brackets

def foo=(value)
value = perform_some_filter(value)
self[:foo] = value
end