Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Class Object to string in Ruby

I m in a situation where i need to convert an Object to string so that i can check for Invalid characters/HTML in any filed of that object.

Here is my function for spam check

def seems_spam?(str)
   flag = str.match(/<.*>/m) || str.match(/http/) || str.match(/href=/)
   Rails.logger.info "** was spam #{flag}"
   flag
end

This method use a string and look for wrong data but i don't know how to convert an object to string and pass to this method. I tried this

@request = Request
spam = seems_spam?(@request.to_s)

Please guide

Thanks

like image 471
Anil D Avatar asked Sep 10 '12 07:09

Anil D


2 Answers

You could try @request.inspect

That will show fields that are publicly accessible

Edit: So are you trying to validate each field on the object?

If so, you could get a hash of field and value pairs and pass each one to your method.

@request.instance_values.each do |field, val|
  if seems_spam? val
  # handle spam
end

If you're asking about implementing a to_s method, Eugene has answered it.

like image 127
kits Avatar answered Oct 05 '22 07:10

kits


You need to create "to_s" method inside your Object class, where you will cycle through all fields of the object and collecting them into one string.

It will look something like this:

def to_s
  attributes.each_with_object("") do |attribute, result|
    result << "#{attribute[1].to_s} "
  end
end

attribute variable is an array with name of the field and value of the field - [id, 1]

Calling @object.to_s will result with a string like "100 555-2342 machete " which you can check for spam.

like image 27
Eugene Dorian Avatar answered Oct 05 '22 07:10

Eugene Dorian