0

My endpoints action takes in a string (originating from an sms).

The string can either consist of:

  1. A business tag within the string which will identify a business
  2. An employees badge number (1000-9999) and a score out of 10 within the string

Examples:

  • '4353 9'
  • '4353 gets a score out of 9'
  • '9 4353'
  • 'score 9 employee 4353'
  • 'bizx thank you'
  • 'thank you bizx'

I cannot control user input. I have o have both types of strings accepted due to cost factors.

I have the following code to try extract the badge number score value or the business tag value.

def endpoints
 if badge_number = get_badge_number(params[:text])
  if score = get_score(params[:text])
   //do something
  end
 elsif business_tag = get_business_tag(params[:text])
  // do stuff
 end
end

def get_badge_number(msg)
 msg.find do |badge_number|
  Employee.exists?(badge_number: badge_number.to_i)
 end
end

def get_score(msg)
 msg.find do |score|
  (1..10).include? score.to_i
 end
end

def get_business_tag(msg)
 msg.find do |tag|
  Business.exists?(tag: tag)
 end
end

As you can see it's turned in to a bit of a mess.

I really need help to efficiently extract the relevant values.

1
  • 2
    When the input can be a mess, generally the solution to extract meaningful data is too. Extracting the numbers can be done with regex grouping. Extracting a name will be a pain. Commented Feb 19, 2014 at 18:11

1 Answer 1

1

You may try to create several classes to handle different kinds of data on the string like:

ScoreSearcher, BadgeNumberSearcher and BusinessTagSearcher

where each of those handle the search by using regexes and return the object if existent or nil. Then on your endpoint, you just need to call this models with the params you got and "do your thing" with the objects if needed.

This still a bit comples, but as @Dave Newton mentioned, its harder to reflect something complex on a simple code, so in my opinion, separate thing in smaller models is the better idea, because it will let you with small thing that do small things. Its also easier to test. =D

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

4 Comments

Thanks Paulo. I'm going to have to open a bounty on this one aren't I?
Why open a bounty? Do you want a more specific answer?
I need help extracting the variables correctly and efficiently.
Try to work with regexes. You cant text your regexes on rubular : rubular.com

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.