Automatically strip values of activerecord attributes

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…

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

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

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs