On May 24, 4:31 pm, Kevin <[email protected]> wrote:
> I'm trying to create a function that will take input in the form "a12345678"
> and output text in the form "a12-34-5678" if and only if the input text is *
> not* in the form "adam smith" The goal is to allow my users to enter either
> names separated by a space, or the student id number into a single search
> field and have the results be returned based on the format of the query.
>
> I came up with the following code in my student model
>
> def self.insert_dashes(term)
> if /^([A-Z]|[a-z]|\d|-){11}$/.match(term)
> term.insert 3, '-'
> term.insert 6,'-'
> end
> end
> def self.find_record(rec)
> if /^([A-Z]|[a-z]|\d|-){11}$/.match(rec)
> student=Student.where(:studentID=>rec).all
> elsif /^([A-Z\s]|[a-z\s])+$/.match(rec)
> split=rec.split ' ',2
> f_name=split.first
> l_name=split.second
> student=Student.where(:fname=>f_name,:lname=>l_name).all
> else
> bar=insert_dashes(rec)
> find_record(bar)
> end
> end
> Can anyone explain what the problem might be or a better approach to
> accomplishing this particular task?
I'm wondering if there's not some whitespace getting added on to the
search term - unless you're stripping it elsewhere, trailing
whitespace will cause this method to run indefinitely - the first time
around insert_dashes will return nil (since it doesn't match the
*exact* character count and the match is fixed at both ends), and that
will then just keep going around.
DRY is nice and all, but here I think you're trading readability (not
to mention halting!) for one repeated line of code. Given that you
*know* what format the argument will be in after calling
insert_dashes, wouldn't it make more sense to just repeat
'Student.where(:studentID=>rec).all' there?
Couple unrelated things:
- I'm not sure why you're alternating amongst different character
classes - this is exactly identical to adding the alternatives *to*
the character class. So:
/^([A-Z]|[a-z]|\d|-){11}$/
can be shortened to:
/^[A-Za-z\d\-]{11}$/
and similarly for the other pattern.
- the code as written will die with StackLevelTooDeep when a user puts
in a name with punctuation (an apostrophe or a hyphen, for instance).
This is most likely a bug.
- the name of this function isn't quite right - you're returning an
*array* from a function named find_record (singular). It would
probably work better to use .first instead of .all in the code above,
or to rename the function to find_records.
Hope this helps!
--Matt Jones
--
You received this message because you are subscribed to the Google Groups "Ruby
on Rails: Talk" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to
[email protected].
For more options, visit this group at
http://groups.google.com/group/rubyonrails-talk?hl=en.