# Automatically strip values of activerecord attributes

**URL:** <https://www.ruby-forum.com/t/automatically-strip-values-of-activerecord-attributes/123023>\
**Category:** Rails\
**Created:** [December 13, 2007, 2:18pm UTC](https://www.ruby-forum.com/t/automatically-strip-values-of-activerecord-attributes/123023 "2007-12-13T14:18:42Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![gabru](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/g/c0e974/32.png) [@gabru](https://www.ruby-forum.com/u/gabru)\
**Post date:** [December 13, 2007, 2:18pm UTC](https://www.ruby-forum.com/t/automatically-strip-values-of-activerecord-attributes/123023/1 "2007-12-13T14:18:42Z")

</div>

i am doing a couple of times the following in my models

class User \< ActiveRecord::Base  
def name=(val)  
write\_attribute :name, val.to\_s.strip  
end  
end

quite clear, it strips the name when setting it.  
now the question: Is it possible to do something like the following …  
and if yes how could i achieve it

class User \< ActiveRecord::Base  
auto\_strip :name, :street  
end

thanks…

---

<div class="post-metadata">

**Author:** ![gabru](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/g/c0e974/32.png) [@gabru](https://www.ruby-forum.com/u/gabru)\
**Post date:** [December 13, 2007, 2:42pm UTC](https://www.ruby-forum.com/t/automatically-strip-values-of-activerecord-attributes/123023/2 "2007-12-13T14:42:36Z")

</div>

This should do the trick:

class User \< ActiveRecord::Base

def self.auto\_strip(\*args)  
args.each do |attribute\_to\_strip|  
class\_eval \<\<-RUBY  
def #{attribute\_to\_strip.to\_s}=(value)  
write\_attribute :#{attribute\_to\_strip.to\_s}, value.strip  
end  
RUBY  
end  
end

auto\_strip :name, :street  
end

---

<div class="post-metadata">

**Author:** ![gabru](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/g/c0e974/32.png) [@gabru](https://www.ruby-forum.com/u/gabru)\
**Post date:** [December 13, 2007, 4:16pm UTC](https://www.ruby-forum.com/t/automatically-strip-values-of-activerecord-attributes/123023/3 "2007-12-13T16:16:21Z")

</div>

hey that looks good … this i what i need.  
thx
