maybe 0.0.1

Sign up to get free protection for your applications and to get access to all the features.
data/.document ADDED
@@ -0,0 +1,5 @@
1
+ README.rdoc
2
+ lib/**/*.rb
3
+ bin/*
4
+ features/**/*.feature
5
+ LICENSE
data/LICENSE ADDED
@@ -0,0 +1,20 @@
1
+ Copyright (c) 2009 Ben Brinckerhoff
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining
4
+ a copy of this software and associated documentation files (the
5
+ "Software"), to deal in the Software without restriction, including
6
+ without limitation the rights to use, copy, modify, merge, publish,
7
+ distribute, sublicense, and/or sell copies of the Software, and to
8
+ permit persons to whom the Software is furnished to do so, subject to
9
+ the following conditions:
10
+
11
+ The above copyright notice and this permission notice shall be
12
+ included in all copies or substantial portions of the Software.
13
+
14
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
data/README.rdoc ADDED
@@ -0,0 +1,72 @@
1
+ = maybe
2
+
3
+ A library for treating nil and non-nil objects in a similar manner. Technically speaking, Maybe is an implemenation of the maybe monad.
4
+
5
+ == Synopsis
6
+
7
+ The Maybe class wraps any value (nil or non-nil) and lets you treat it as non-nil.
8
+
9
+ "hello".upcase #=> "HELLO"
10
+ nil.upcase #=> NoMethodError: undefined method `upcase' for nil:NilClass
11
+ Maybe.new("hello").upcase.value #=> "HELLO"
12
+ Maybe.new(nil).upcase.value #=> nil
13
+
14
+ You can also use the method Maybe for convenience. The following are equivalent:
15
+
16
+ Maybe.new("hello").value #=> "hello"
17
+ Maybe("hello").value #=> "hello"
18
+
19
+ When you call Maybe.new with a value, that value is wrapped in a Maybe object. Whenever you call methods on that object, it does a simple check: if the wrapped value is nil, then it returns another Maybe object that wraps nil. If the wrapped object is not nil, it calls the method on that object, then wraps it back up in a Maybe object.
20
+
21
+ This is especially handy for long chains of method calls, any of which could return nil.
22
+
23
+ # foo, bar, and/or baz could return nil, but this will still work
24
+ Maybe.new(foo).bar(1).baz(:x)
25
+
26
+ Here's a real world example. Instead of writing this:
27
+
28
+ if(customer && customer.order && customer.order.id==newest_customer_id)
29
+ # ... do something with customer
30
+ end
31
+
32
+ just write this:
33
+
34
+ if(Maybe.new(customer).order.id.value==newest_customer_id)
35
+ # ... do something with customer
36
+ end
37
+
38
+ == Examples
39
+
40
+ Maybe.new("10") #=> A Maybe object, wrapping "10"
41
+
42
+ Maybe.new("10").to_i #=> A Maybe object, wrapping 10
43
+
44
+ Maybe.new("10").to_i.value #=> 10
45
+
46
+ Maybe.new(nil) #=> A Maybe object, wrapping nil
47
+
48
+ Maybe.new(nil).to_i #=> A Maybe object, still wrapping nil
49
+
50
+ Maybe.new(nil).to_i.value #=> nil
51
+
52
+ == Related Reading
53
+
54
+ * {MenTaLguY has a great tutorial on Monads in Ruby over at Moonbase}[http://moonbase.rydia.net/mental/writings/programming/monads-in-ruby/00introduction.html]
55
+ * {Oliver Steele explores the problem in depth and looks at a number of different solutions}[http://osteele.com/archives/2007/12/cheap-monads]
56
+ * {Reg Braithwaite explores this same problem and comes up with a different, but very cool solution in Ruby}[http://weblog.raganwald.com/2008/01/objectandand-objectme-in-ruby.html]
57
+ * {Weave Jester has another solution, inspired by the Maybe monad}[http://weavejester.com/node/10]
58
+
59
+ == Note on Patches/Pull Requests
60
+
61
+ * Fork the project.
62
+ * Make your feature addition or bug fix.
63
+ * Add tests for it. This is important so I don't break it in a
64
+ future version unintentionally.
65
+ * Commit, do not mess with rakefile, version, or history.
66
+ (if you want to have your own version, that is fine but
67
+ bump version in a commit by itself I can ignore when I pull)
68
+ * Send me a pull request. Bonus points for topic branches.
69
+
70
+ == Copyright
71
+
72
+ Copyright (c) 2010 Ben Brinckerhoff. See LICENSE for details.
data/Rakefile ADDED
@@ -0,0 +1,57 @@
1
+ require 'rubygems'
2
+ require 'rake'
3
+
4
+ begin
5
+ require 'jeweler'
6
+ Jeweler::Tasks.new do |gem|
7
+ gem.name = "maybe"
8
+ gem.summary = %Q{A library for treating nil and non-nil objects in a similar manner.}
9
+ gem.description = %Q{A library for treating nil and non-nil objects in a similar manner. Technically speaking, Maybe is an implemenation of the maybe monad. The Maybe class wraps any value (nil or non-nil) and lets you treat it as non-nil.}
10
+ gem.email = "ben@devver.net"
11
+ gem.homepage = "http://github.com/bhb/maybe"
12
+ gem.authors = ["Ben Brinckerhoff"]
13
+ gem.add_development_dependency("mocha", "~> 0.9.8")
14
+ # gem is a Gem::Specification... see http://www.rubygems.org/read/chapter/20 for additional settings
15
+ end
16
+ Jeweler::GemcutterTasks.new
17
+ rescue LoadError
18
+ puts "Jeweler (or a dependency) not available. Install it with: sudo gem install jeweler"
19
+ end
20
+
21
+ require 'rake/testtask'
22
+ Rake::TestTask.new(:test) do |test|
23
+ test.libs << 'lib' << 'test'
24
+ test.pattern = 'test/**/*_test.rb'
25
+ test.verbose = true
26
+ end
27
+
28
+ begin
29
+ require 'rcov/rcovtask'
30
+ Rcov::RcovTask.new do |test|
31
+ test.libs << 'test'
32
+ test.pattern = 'test/**/*_test.rb'
33
+ test.verbose = true
34
+ end
35
+ rescue LoadError
36
+ task :rcov do
37
+ abort "RCov is not available. In order to run rcov, you must: sudo gem install spicycode-rcov"
38
+ end
39
+ end
40
+
41
+ task :test => :check_dependencies
42
+
43
+ task :default => :test
44
+
45
+ require 'rake/rdoctask'
46
+ Rake::RDocTask.new do |rdoc|
47
+ if File.exist?('VERSION')
48
+ version = File.read('VERSION')
49
+ else
50
+ version = ""
51
+ end
52
+
53
+ rdoc.rdoc_dir = 'rdoc'
54
+ rdoc.title = "maybe #{version}"
55
+ rdoc.rdoc_files.include('README*')
56
+ rdoc.rdoc_files.include('lib/**/*.rb')
57
+ end
data/VERSION ADDED
@@ -0,0 +1 @@
1
+ 0.0.1
data/lib/maybe.rb ADDED
@@ -0,0 +1,64 @@
1
+ def Maybe(value)
2
+ Maybe.new(value)
3
+ end
4
+
5
+ class Maybe
6
+
7
+ instance_methods.reject { |method_name| method_name =~ /^__/ }.each { |method_name| undef_method method_name }
8
+
9
+ def initialize(value)
10
+ @value = value
11
+ self.join
12
+ end
13
+
14
+ def method_missing(method_name, *args)
15
+ self.fmap do |value|
16
+ value.send(method_name,*args) do |*block_args|
17
+ yield(*block_args) if block_given?
18
+ end
19
+ end
20
+ end
21
+
22
+ def value(value_if_nil=nil)
23
+ if(value_if_nil!=nil && @value==nil)
24
+ value_if_nil
25
+ else
26
+ @value
27
+ end
28
+ end
29
+
30
+ # Given that the value is of type A
31
+ # takes a function from A->M[B] and returns
32
+ # M[B] (a monad with a value of type B)
33
+ def pass
34
+ fmap {|*block_args| yield(*block_args)}.join
35
+ end
36
+
37
+ # Given that the value is of type A
38
+ # takes a function from A->B and returns
39
+ # M[B] (a monad with a value of type B)
40
+ def fmap
41
+ if(@value==nil)
42
+ self
43
+ else
44
+ Maybe.new(yield(@value))
45
+ end
46
+ end
47
+
48
+ def nil?
49
+ @value==nil
50
+ end
51
+
52
+ def join
53
+ if(@value.is_a?(Maybe))
54
+ @value = value.value
55
+ end
56
+ self
57
+ end
58
+
59
+ # for testing purposes
60
+ def value=(value)
61
+ @value = value
62
+ end
63
+
64
+ end
@@ -0,0 +1,122 @@
1
+ require File.expand_path("test_helper", File.dirname(__FILE__))
2
+ require 'cgi'
3
+
4
+ class MaybeTest < Test::Unit::TestCase
5
+
6
+ def test_initialize__performs_join
7
+ assert_equal 1, Maybe.new(Maybe.new(1)).value
8
+ end
9
+
10
+ def test_initialize__never_calls_pass_on_nested_maybe
11
+ Maybe.any_instance.expects(:pass).never
12
+ Maybe.new(Maybe.new(1)).value
13
+ end
14
+
15
+ def test_call_match_operator
16
+ assert_equal nil, (Maybe.new(nil)=~/b/).value
17
+ assert_equal 1, (Maybe.new('abc')=~/b/).value
18
+ end
19
+
20
+ def test_call_method_defined_on_object
21
+ assert_equal nil, (Maybe.new(nil).to_s).value
22
+ assert_equal "1", (Maybe.new(1).to_s).value
23
+ end
24
+
25
+ def test_method
26
+ assert_equal nil, Maybe.new(nil).to_int.value
27
+ assert_equal 2, Maybe.new(2.3).to_int.value
28
+ end
29
+
30
+ def test_method_with_block
31
+ assert_equal nil, Maybe.new(nil).map{|x|x*2}.value
32
+ assert_equal [2,4,6], Maybe.new([1,2,3]).map{|x|x*2}.value
33
+ end
34
+
35
+ def test_method__calling_method_doesnt_change_value
36
+ x = Maybe.new(1)
37
+ x.to_s
38
+ assert_equal 1, x.value
39
+ end
40
+
41
+ def test_method_with_arg_and_block
42
+ assert_equal nil, Maybe.new(nil).gsub(/x/) {|m| m.upcase}.value
43
+ str = Maybe.new('x').gsub(/x/) do |m|
44
+ m.upcase
45
+ end
46
+ assert_equal 'X', str.value
47
+ end
48
+
49
+ def test_join__doesnt_call_pass
50
+ Maybe.any_instance.expects(:pass).never
51
+ m = Maybe.new(nil)
52
+ m.value = Maybe.new(1)
53
+ m.join
54
+ end
55
+
56
+ def test_pass__with_cgi_unescape
57
+ # using CGI::unescape because that's the first function I had problems with
58
+ # when implementing Maybe
59
+ assert_equal nil, Maybe.new(nil).pass {|v|CGI.unescapeHTML(v)}.value
60
+ assert_equal '&', Maybe.new('&amp;').pass {|v|CGI.unescapeHTML(v)}.value
61
+ end
62
+
63
+ def test_nil
64
+ assert_equal true, Maybe.new(nil).nil?
65
+ assert_equal false, Maybe.new(1).nil?
66
+ end
67
+
68
+ def test_value__returns_value_with_no_params
69
+ assert_equal nil, Maybe.new(nil).value
70
+ assert_equal 1, Maybe.new(1).value
71
+ end
72
+
73
+ def test_value__with_default
74
+ assert_equal "", Maybe.new(nil).value("")
75
+ assert_equal 1, Maybe.new(1).value("1")
76
+ assert_equal nil, Maybe.new(nil).value(nil)
77
+ assert_equal true, Maybe.new(true).value(nil)
78
+ assert_equal false, Maybe.new(nil).value(false)
79
+ assert_equal 1, Maybe.new(1).value(false)
80
+ end
81
+
82
+ # the connection between fmap and pass (translated from)
83
+ # http://james-iry.blogspot.com/2007/10/monads-are-elephants-part-3.html
84
+ # scala version: m map f ≡ m flatMap {x => unit(f(x))}
85
+ # note that in my code map == fmap && unit==Maybe.new && flatMap==pass
86
+ def test_monad_rule_0
87
+ f = lambda {|x| x*2}
88
+ m = Maybe.new(5)
89
+ assert_equal m.fmap(&f), m.pass {|x| Maybe.new(f[x])}
90
+ end
91
+
92
+ # monad rules taken from http://moonbase.rydia.net/mental/writings/programming/monads-in-ruby/01identity
93
+ # and http://james-iry.blogspot.com/2007_10_01_archive.html
94
+
95
+ #1. Calling pass on a newly-wrapped value should have the same effect as giving that value directly to the block.
96
+ # (this is actually the second law at http://james-iry.blogspot.com/2007/10/monads-are-elephants-part-3.html)
97
+ # scala version: unit(x) flatMap f ≡ f(x)
98
+ def test_monad_rule_1
99
+ f = lambda {|y| Maybe.new(y.to_s)}
100
+ x = 1
101
+ assert_equal f[x], Maybe.new(x).pass {|y| f[y]}.value
102
+ end
103
+
104
+ #2. pass with a block that simply calls wrap on its value should produce the exact same values, wrapped up again.
105
+ # (this is actually the first law at http://james-iry.blogspot.com/2007/10/monads-are-elephants-part-3.html)
106
+ # scala version: m flatMap unit ≡ m
107
+ def test_monad_rule_2
108
+ x = Maybe.new(1)
109
+ assert_equal x.value, x.pass {|y| Maybe.new(y)}.value
110
+ end
111
+
112
+ #3. nesting pass blocks should be equivalent to calling them sequentially
113
+ def test_monad_rule_3
114
+ f = lambda {|x| Maybe.new(x*2)}
115
+ g = lambda {|x| Maybe.new(x+1)}
116
+ m = Maybe.new(3)
117
+ n = Maybe.new(3)
118
+ assert_equal m.pass{|x| f[x]}.pass{|x|g[x]}.value, n.pass{|x| f[x].pass{|y|g[y]}}.value
119
+ end
120
+
121
+
122
+ end
@@ -0,0 +1,10 @@
1
+ require 'rubygems'
2
+ require 'test/unit'
3
+ require 'mocha'
4
+
5
+ $LOAD_PATH.unshift(File.dirname(__FILE__))
6
+ $LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib'))
7
+ require 'maybe'
8
+
9
+ class Test::Unit::TestCase
10
+ end
metadata ADDED
@@ -0,0 +1,74 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: maybe
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.0.1
5
+ platform: ruby
6
+ authors:
7
+ - Ben Brinckerhoff
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+
12
+ date: 2010-01-30 00:00:00 -07:00
13
+ default_executable:
14
+ dependencies:
15
+ - !ruby/object:Gem::Dependency
16
+ name: mocha
17
+ type: :development
18
+ version_requirement:
19
+ version_requirements: !ruby/object:Gem::Requirement
20
+ requirements:
21
+ - - ~>
22
+ - !ruby/object:Gem::Version
23
+ version: 0.9.8
24
+ version:
25
+ description: A library for treating nil and non-nil objects in a similar manner. Technically speaking, Maybe is an implemenation of the maybe monad. The Maybe class wraps any value (nil or non-nil) and lets you treat it as non-nil.
26
+ email: ben@devver.net
27
+ executables: []
28
+
29
+ extensions: []
30
+
31
+ extra_rdoc_files:
32
+ - LICENSE
33
+ - README.rdoc
34
+ files:
35
+ - .document
36
+ - .gitignore
37
+ - LICENSE
38
+ - README.rdoc
39
+ - Rakefile
40
+ - VERSION
41
+ - lib/maybe.rb
42
+ - test/maybe_test.rb
43
+ - test/test_helper.rb
44
+ has_rdoc: true
45
+ homepage: http://github.com/bhb/maybe
46
+ licenses: []
47
+
48
+ post_install_message:
49
+ rdoc_options:
50
+ - --charset=UTF-8
51
+ require_paths:
52
+ - lib
53
+ required_ruby_version: !ruby/object:Gem::Requirement
54
+ requirements:
55
+ - - ">="
56
+ - !ruby/object:Gem::Version
57
+ version: "0"
58
+ version:
59
+ required_rubygems_version: !ruby/object:Gem::Requirement
60
+ requirements:
61
+ - - ">="
62
+ - !ruby/object:Gem::Version
63
+ version: "0"
64
+ version:
65
+ requirements: []
66
+
67
+ rubyforge_project:
68
+ rubygems_version: 1.3.5
69
+ signing_key:
70
+ specification_version: 3
71
+ summary: A library for treating nil and non-nil objects in a similar manner.
72
+ test_files:
73
+ - test/maybe_test.rb
74
+ - test/test_helper.rb