rails_has_elegance
rails_has_elegance

Reputation: 1692

Rails 3 - Check if string/text includes a certain word/character via regex in controller

I am working on a quoting mechanism in my app, where it should be possible to simply type #26, for example, in the comment form in order to quote comment 26 of that topic.
To check if a user wants to quote one or more comments in the first place, I put an if condition after my current_user.comments.build and before @comment.save.
But, just to make my question a bit more general and easier to adapt:

if @comment.content.include?(/\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i)

I want something like this. That example was for checking if the comment's content includes emails. But logically I get an "can't convert regexp to string" error.

How can you do the include? method in rails with an regexp? So, to check whether a text includes a string of a certain regex format?

Or is the controller the wrong place for such regex actions?

Upvotes: 25

Views: 52164

Answers (3)

Carpela
Carpela

Reputation: 2195

To match the nature of .include?

 stringObj.match(/regex/).present?

Would give similar true/false outcomes if you're using Rails (or ActiveSupport)

Upvotes: 6

calvin
calvin

Reputation: 347

There's also

if @comment.content =~ /regex/

If you had an array of all previous comments @prev_comments and wanted to replace them all in one shot, you could:

pattern = /#(\d+)/

@comment.content.gsub(pattern) do 
  cur_match = Regexp.last_match
  idx = cur_match[1].to_i - 1
  @prev_comments[idx]
end

Trick is using Regexp.last_match to get the current match, which made me wonder if it was thread safe. It is, apparently.

adapted (stolen) from the below more general String extension

class String
  def js_replace(pattern, &block)
    gsub(pattern) do |_|
      md = Regexp.last_match
      args = [md.to_s, md.captures, md.begin(0), self].flatten
      block.call(*args)
    end
  end
end

Source: http://vemod.net/string-js_replace

Upvotes: 9

Anna Billstrom
Anna Billstrom

Reputation: 2492

I do ruby regex'es this way:

stringObj.match(/regex/)

Upvotes: 57

Related Questions