root/linen/trunk/examples/math.rb

Revision 564, 1.6 kB (checked in by bbleything, 2 months ago)
  • refix the copyright. doh.
  • Property svn:keywords set to Date Rev Author URL Id
Line 
1 #!/usr/bin/env ruby
2 #
3 # Demonstrates a simple plugin that does basic math.
4 #
5 # == Authors
6 #
7 # * Ben Bleything <bbleything@laika.com>
8 #
9 # == Copyright
10 #
11 # Copyright (c) 2008 LAIKA, Inc.
12 #
13 # This code released under the terms of the BSD license.
14 #
15 # == Version
16 #
17 #  $Id$
18 #
19
20 require 'rubygems'
21 require 'linen'
22
23 class MathPlugin < Linen::Plugin
24     description "Perform simple mathematical operations.  Currently supports addition, subtraction, multiplication, and division."
25
26     floating_point_regex = /^\d+(\.\d+)?$/
27
28     argument :lhs,
29              :prompt  => 'Please enter the left-hand operand: ',
30              :regex   => floating_point_regex,
31              :process => Proc.new {|i| i.to_f }
32
33     argument :rhs,
34              :prompt  => 'Please enter the right-hand operand: ',
35              :regex   => floating_point_regex,
36              :process => Proc.new {|i| i.to_f }
37
38     command :add do
39         help_message "Adds two operands. (lhs + rhs)"
40
41         required_arguments :lhs, :rhs
42
43         action do
44             say "#{lhs} + #{rhs} = #{lhs + rhs}"
45         end
46     end
47
48     command :subtract do
49         help_message "Subtracts the second operand from the first. (lhs - rhs)"
50
51         required_arguments :lhs, :rhs
52
53         action do
54             say "#{lhs} - #{rhs} = #{lhs - rhs}"
55         end
56     end
57
58     command :multiply do
59         help_message "Multiplies two operands. (lhs * rhs)"
60
61         required_arguments :lhs, :rhs
62
63         action do
64             say "#{lhs} * #{rhs} = #{lhs * rhs}"
65         end
66     end
67
68     command :divide do
69         help_message "Divides the first operand by the second. (lhs / rhs)"
70
71         required_arguments :lhs, :rhs
72
73         action do
74             say "#{lhs} / #{rhs} = #{lhs / rhs}"
75         end
76     end
77 end
78
79 Linen::CLI.prompt = "math > "
80 Linen.start
Note: See TracBrowser for help on using the browser.