[Highline] Custom validation

G

Gavin Kistner

--Apple-Mail-1-775425937
Content-Transfer-Encoding: 7bit
Content-Type: text/plain;
charset=US-ASCII;
delsp=yes;
format=flowed

For this week's Ruby Quiz, I would like to use Highline for user
input. I understand how to get it to validate input based on a
regexp, but I'd like to do more (after that is automatically handled,
if possible).

After I get Highline to ensure that a user's input matches a square
on the board (which can be done with the simple regexp) I'd like it
to further ensure that there is a piece on the board, and that piece
belongs to the player whose turn it is.

Is it possible to pass a custom post-validation block to to a
Highline::Question, which will use the return value of that block to
determine if the question should be asked again? (If not, consider
this a feature request.)

I suppose it's not much different to do:

piece = nil
while !piece
loc = ask( "Piece to move:" ){ |q|
q.responses[ :not_valid ] = "Please specify a board
location, such as a8 or c3"
q.validate = /[a-h][1-8]/i
}
piece = board[ loc ]
if piece && piece.color != board.turn_color
puts "You can't move the piece at #{loc}, because it is not
yours!"
piece = nil
end
end
 
G

Gavin Kistner

--Apple-Mail-2-775755153
Content-Transfer-Encoding: 7bit
Content-Type: text/plain;
charset=US-ASCII;
delsp=yes;
format=flowed

Is it possible to pass a custom post-validation block to to a
Highline::Question, which will use the return value of that block
to determine if the question should be asked again? (If not,
consider this a feature request.)

The answer is "RTFM past the first sentence describing the
Question#validate property, onto the second sentence."

Sorry for the noise :p

--Apple-Mail-2-775755153--
 
J

James Edward Gray II

The answer is "RTFM past the first sentence describing the
Question#validate property, onto the second sentence."

Sorry for the noise :p

Looks like you found your answer, but for the sake of completeness
HighLine validation can be done with a Proc:

ask("Piece to move: ") { |q| q.validate = lambda { |move| is_legal?
move } }

James Edward Gray II
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,065
Latest member
OrderGreenAcreCBD

Latest Threads

Top