How to cycle over all self.xx elements performing a method?


#1

Hi,

I would like to perform CGI.escapeHTML to all var’s before save,
somthing like
(that obviously dont work)
self.each do |attr|
attr = CGI.escapeHTML(attr) if attr
end

Thanks
Scot


#2

I would like to perform CGI.escapeHTML to all var’s before save,

Wouldn’t this be a straightforward application of the before_save()
callback in your model(s)?


#3

Mark T. wrote:

I would like to perform CGI.escapeHTML to all var’s before save,

Wouldn’t this be a straightforward application of the before_save()
callback in your model(s)?

yes, this is how I am currently doing it, maybe I have miss understood
how before save works

before_save :encodeTags

#removes html tags and encode &'s etc… CGI.escapeHTML()
def removeTags
self.name = strip_tags(self.name) if self.name
self.author = strip_tags(self.author) if self.author
self.author_email = strip_tags(self.author_email) if
self.author_email
self.url = strip_tags(self.url) if self.url
self.repository = strip_tags(self.repository) if self.repository
end

I want to be able just to cycle over each attribute without having to
specify a line for each one.


#4

Hi Scot,

scot wrote:

before_save :encodeTags
def removeTags
end
I assume you recognize the mismatch here and that it’s a typo.

I want to be able just to cycle over each attribute
without having to specify a line for each one.

Scaffold a sandbox app over a table and look at the list method to see
how
Rails generates the column headings. That’s how you do it.

hth,
Bill


#5

I want to be able just to cycle over each attribute without having to
specify a line for each one.
not tested, just writting by heart but i’m pretty sure it should work

self.attributes.each do |key,value|
self[key] = strip_tags(self[key]) if self[key]
end

regards,

javier ramirez

Estamos de estreno… si necesitas llevar el control de tus gastos
visita http://www.gastosgem.com !!Es gratis!!


#6

Maybe something like…

attribute_names.select { |a| attribute_present? a }.each { |a| self[a]
= strip_tags(self[a]) }


#7

John B. wrote:

Maybe something like…

attribute_names.select { |a| attribute_present? a }.each { |a| self[a]
= strip_tags(self[a]) }

thanks everyone, this is how I did it in the end, however teh above
solution seems to look nice too.

add new lines as required

CGI.escapeHTML() or ERB::Util::html_escape

def encodeTags

string_attributes = {}
self.attributes.each do |each_name, each_attribute|
if each_attribute.kind_of? String
string_attributes[each_name] =
ERB::Util::html_escape(each_attribute)
end
end
self.attributes = string_attributes

end