0

ok so assume I have a variable that will be changing in every controller. @keyword and I am trying to find out if a specified keyword is in a post. My code is

= if posting.body =~ /<%= @keyword %>/
   then post //pseudocode here not my actual code. this isn't needed

I tried using .html_safe (I am using haml btw) and .raw(i wouldn't normally do this, but was suggested on another forum question that I didn't write. I only want to pass that instance variable from the controller. I don't think this would be hard, but I know there is a way.

3 Answers 3

1
= if posting.body =~ /#{@keyword}/

Try this and see if it works. I think this is how ruby is interpolated inside a regex.

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

Comments

1

The =~ operator matches the regular expression against a string, and it returns either the offset of the match from the string if it is found, otherwise nil.

See here for the documentation.

If you are looking keyword in REGEX then your syntax will be:

posting.body =~ /^#{URI::regexp}$/

For variable:

posting.body =~ /^#{@keyword}$/

1 Comment

This way didn't work because of the caret and dollarsign. It could be just based on what I'm doing with my application though.
0

Try

= if posting.body =~ /#{@keyword}/
  then post

The <%= something %> in template is used to output some data to the response body. I believe that the code after = is just normal Ruby code.

BTW, you may need to escape the @keyword content, in case that it contains some special characters used in regular expression (. for example).

= if posting.body =~ /#{Regexp.escape(@keyword)}/
  then post

Comments

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.