0

I'm trying to write code that will let me search the content submitted through a form and find the email address in the content. Below is the code, and the error message I'm receiving.

Error: undefined method `match' for {"content"=>"this is a test testemail@gmail.com"}:ActionController::Parameters

Code:

class ChallengesController < ApplicationController
  def create
    @challenge = current_user.challenges.build(challenge_params)
    challenge_params.match(/\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b/i)
    # ...
  end

  private

  def challenge_params
    params.require(:challenge).permit(:content)
  end 
end
Stefan
  • 109,145
  • 14
  • 143
  • 218
  • What is your question? – sawa Dec 16 '15 at 14:01
  • 1
    Using regular expressions to find valid email strings is very difficult, because there are [a huge number of variations on valid addresses](http://stackoverflow.com/questions/201323/using-a-regular-expression-to-validate-an-email-address). – the Tin Man Dec 16 '15 at 16:39

2 Answers2

1

You are applying match on a Hash.

challenge_params is a Hash. Going by the error message, this hash contains a key content which is where you want to use with match, hence rewriting the match line to:

challenge_params["content"].match(/\b[A-Z0-9\._%+-]+@[A-Z0-9\.-]+\.[A-Z]{2,4}\b/i)
the Tin Man
  • 158,662
  • 42
  • 215
  • 303
shivam
  • 16,048
  • 3
  • 56
  • 71
0

I'm new to ruby so my answer may be very "amateur-ish", but sometimes the simplest ideas are the best... The way I would do this is search for index of @ sign. Then analyze each character before and after the sign until you get to blank space and save those index numbers. Use those index numbers to extract the email address from your string.

def email_address(str)
at_index = str.index('@')
temp = (at_index - 1)
while str[temp] != ' '
    temp -= 1
end
begining_index = (temp + 1)
temp = (at_index + 1)
while str[temp] != ' '
    temp += 1
end
end_index = temp
return str[begining_index..end_index]

end

Margal
  • 17
  • 5
  • 1
    problem with this approach is, what if you get a string like: `"some random special chars 1@#$%! my email: test@gmail.com"` – shivam Dec 16 '15 at 14:31
  • While the description is nice, you need to show code. We appreciate that you're new to Ruby, however solutions to problems almost always need code. – the Tin Man Dec 16 '15 at 16:35
  • @theTinMan: sorry about that. I edited my original answer including sample code... – Margal Dec 16 '15 at 18:56