10

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

2 Answers 2

9

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.

Sign up to request clarification or add additional context in comments.

1 Comment

@request.inspect , return hash data as to_s did, like this { "first_name"=>"Anil", "last_name"=>"Dutt", "phone_number"=>"123456^%%^#GFDF", "notes"=>"test...67$^*%$*^$^%$^%RFHG DCSDHF$\#@$\#$$@}
2

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.

3 Comments

result << "#{attribute[1].to_s} ", what is 1 here , index? or do i need to give name of each attribute?
1 is index, you don't need to give name of each attribute. Calling attribute[1] will give you the value of an attribute.
Well then to_s method is not for you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.