memoize_delegate 0.1.0

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: 7f3a550ed41ffa439180468b964a7c69b31dcef4
4
+ data.tar.gz: 2b210d9c8cd314437dfec2fc0236d5d30982c3ec
5
+ SHA512:
6
+ metadata.gz: 4a6453fb573aeb5a6da330e996c9a76fce6c310a0da137dc0599a41d9c1d475536d620f36e80a5d8f252cc1d7c615cc1a602190987cbcff17376da7c03eb4176
7
+ data.tar.gz: 1a37631c661590b14df3d8ba361b2732c807480653a80eba71bf971498cdbfa2cf924307157454f7d2adeed9e3b61912ba884518f9a6de4bf992f77f3f8f19c3
@@ -0,0 +1,12 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /Gemfile.lock
4
+ /_yardoc/
5
+ /coverage/
6
+ /doc/
7
+ /pkg/
8
+ /spec/reports/
9
+ /tmp/
10
+
11
+ # rspec failure tracking
12
+ .rspec_status
data/.rspec ADDED
@@ -0,0 +1,2 @@
1
+ --format documentation
2
+ --color
@@ -0,0 +1,5 @@
1
+ sudo: false
2
+ language: ruby
3
+ rvm:
4
+ - 2.3.4
5
+ before_install: gem install bundler -v 1.14.6
@@ -0,0 +1,74 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ In the interest of fostering an open and welcoming environment, we as
6
+ contributors and maintainers pledge to making participation in our project and
7
+ our community a harassment-free experience for everyone, regardless of age, body
8
+ size, disability, ethnicity, gender identity and expression, level of experience,
9
+ nationality, personal appearance, race, religion, or sexual identity and
10
+ orientation.
11
+
12
+ ## Our Standards
13
+
14
+ Examples of behavior that contributes to creating a positive environment
15
+ include:
16
+
17
+ * Using welcoming and inclusive language
18
+ * Being respectful of differing viewpoints and experiences
19
+ * Gracefully accepting constructive criticism
20
+ * Focusing on what is best for the community
21
+ * Showing empathy towards other community members
22
+
23
+ Examples of unacceptable behavior by participants include:
24
+
25
+ * The use of sexualized language or imagery and unwelcome sexual attention or
26
+ advances
27
+ * Trolling, insulting/derogatory comments, and personal or political attacks
28
+ * Public or private harassment
29
+ * Publishing others' private information, such as a physical or electronic
30
+ address, without explicit permission
31
+ * Other conduct which could reasonably be considered inappropriate in a
32
+ professional setting
33
+
34
+ ## Our Responsibilities
35
+
36
+ Project maintainers are responsible for clarifying the standards of acceptable
37
+ behavior and are expected to take appropriate and fair corrective action in
38
+ response to any instances of unacceptable behavior.
39
+
40
+ Project maintainers have the right and responsibility to remove, edit, or
41
+ reject comments, commits, code, wiki edits, issues, and other contributions
42
+ that are not aligned to this Code of Conduct, or to ban temporarily or
43
+ permanently any contributor for other behaviors that they deem inappropriate,
44
+ threatening, offensive, or harmful.
45
+
46
+ ## Scope
47
+
48
+ This Code of Conduct applies both within project spaces and in public spaces
49
+ when an individual is representing the project or its community. Examples of
50
+ representing a project or community include using an official project e-mail
51
+ address, posting via an official social media account, or acting as an appointed
52
+ representative at an online or offline event. Representation of a project may be
53
+ further defined and clarified by project maintainers.
54
+
55
+ ## Enforcement
56
+
57
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
58
+ reported by contacting the project team at mathieu@justbudget.com. All
59
+ complaints will be reviewed and investigated and will result in a response that
60
+ is deemed necessary and appropriate to the circumstances. The project team is
61
+ obligated to maintain confidentiality with regard to the reporter of an incident.
62
+ Further details of specific enforcement policies may be posted separately.
63
+
64
+ Project maintainers who do not follow or enforce the Code of Conduct in good
65
+ faith may face temporary or permanent repercussions as determined by other
66
+ members of the project's leadership.
67
+
68
+ ## Attribution
69
+
70
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
71
+ available at [http://contributor-covenant.org/version/1/4][version]
72
+
73
+ [homepage]: http://contributor-covenant.org
74
+ [version]: http://contributor-covenant.org/version/1/4/
data/Gemfile ADDED
@@ -0,0 +1,4 @@
1
+ source 'https://rubygems.org'
2
+
3
+ # Specify your gem's dependencies in memoize_delegate.gemspec
4
+ gemspec
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2017 Mathieu Jobin
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
@@ -0,0 +1,41 @@
1
+ # MemoizeDelegate
2
+
3
+ Welcome to your new gem! In this directory, you'll find the files you need to be able to package up your Ruby library into a gem. Put your Ruby code in the file `lib/memoize_delegate`. To experiment with that code, run `bin/console` for an interactive prompt.
4
+
5
+ TODO: Delete this and the text above, and describe your gem
6
+
7
+ ## Installation
8
+
9
+ Add this line to your application's Gemfile:
10
+
11
+ ```ruby
12
+ gem 'memoize_delegate'
13
+ ```
14
+
15
+ And then execute:
16
+
17
+ $ bundle
18
+
19
+ Or install it yourself as:
20
+
21
+ $ gem install memoize_delegate
22
+
23
+ ## Usage
24
+
25
+ TODO: Write usage instructions here
26
+
27
+ ## Development
28
+
29
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
30
+
31
+ To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org).
32
+
33
+ ## Contributing
34
+
35
+ Bug reports and pull requests are welcome on GitHub at https://github.com/[USERNAME]/memoize_delegate. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [Contributor Covenant](http://contributor-covenant.org) code of conduct.
36
+
37
+
38
+ ## License
39
+
40
+ The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT).
41
+
@@ -0,0 +1,6 @@
1
+ require "bundler/gem_tasks"
2
+ require "rspec/core/rake_task"
3
+
4
+ RSpec::Core::RakeTask.new(:spec)
5
+
6
+ task :default => :spec
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require "bundler/setup"
4
+ require "memoize_delegate"
5
+
6
+ # You can add fixtures and/or initialization code here to make experimenting
7
+ # with your gem easier. You can also use a different console, if you like.
8
+
9
+ # (If you use this, don't forget to add pry to your Gemfile!)
10
+ # require "pry"
11
+ # Pry.start
12
+
13
+ require "irb"
14
+ IRB.start(__FILE__)
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+ set -vx
5
+
6
+ bundle install
7
+
8
+ # Do any other automated setup that you need to do here
@@ -0,0 +1,6 @@
1
+ require "memoize_delegate/version"
2
+ require "memoize_delegate/delegation"
3
+
4
+ module MemoizeDelegate
5
+ # Your code goes here...
6
+ end
@@ -0,0 +1,224 @@
1
+ require 'set'
2
+
3
+ class Module
4
+ # Error generated by +memoize_delegate+ when a method is called on +nil+ and +allow_nil+
5
+ # option is not used.
6
+ class DelegationError < NoMethodError; end
7
+
8
+ RUBY_RESERVED_KEYWORDS = %w(alias and BEGIN begin break case class def defined? do
9
+ else elsif END end ensure false for if in module next nil not or redo rescue retry
10
+ return self super then true undef unless until when while yield)
11
+ DELEGATION_RESERVED_KEYWORDS = %w(_ arg args block)
12
+ DELEGATION_RESERVED_METHOD_NAMES = Set.new(
13
+ RUBY_RESERVED_KEYWORDS + DELEGATION_RESERVED_KEYWORDS
14
+ ).freeze
15
+
16
+ # Provides a +memoize_delegate+ class method to easily expose contained objects'
17
+ # public methods as your own.
18
+ #
19
+ # ==== Options
20
+ # * <tt>:to</tt> - Specifies the target object
21
+ # * <tt>:prefix</tt> - Prefixes the new method with the target name or a custom prefix
22
+ # * <tt>:allow_nil</tt> - if set to true, prevents a +NoMethodError+ from being raised
23
+ #
24
+ # The macro receives one or more method names (specified as symbols or
25
+ # strings) and the name of the target object via the <tt>:to</tt> option
26
+ # (also a symbol or string).
27
+ #
28
+ # Delegation is particularly useful with Active Record associations:
29
+ #
30
+ # class Greeter < ActiveRecord::Base
31
+ # def hello
32
+ # 'hello'
33
+ # end
34
+ #
35
+ # def goodbye
36
+ # 'goodbye'
37
+ # end
38
+ # end
39
+ #
40
+ # class Foo < ActiveRecord::Base
41
+ # belongs_to :greeter
42
+ # memoize_delegate :hello, to: :greeter
43
+ # end
44
+ #
45
+ # Foo.new.hello # => "hello"
46
+ # Foo.new.goodbye # => NoMethodError: undefined method `goodbye' for #<Foo:0x1af30c>
47
+ #
48
+ # Multiple memoize_delegates to the same target are allowed:
49
+ #
50
+ # class Foo < ActiveRecord::Base
51
+ # belongs_to :greeter
52
+ # memoize_delegate :hello, :goodbye, to: :greeter
53
+ # end
54
+ #
55
+ # Foo.new.goodbye # => "goodbye"
56
+ #
57
+ # Methods can be memoize_delegated to instance variables, class variables, or constants
58
+ # by providing them as a symbols:
59
+ #
60
+ # class Foo
61
+ # CONSTANT_ARRAY = [0,1,2,3]
62
+ # @@class_array = [4,5,6,7]
63
+ #
64
+ # def initialize
65
+ # @instance_array = [8,9,10,11]
66
+ # end
67
+ # memoize_delegate :sum, to: :CONSTANT_ARRAY
68
+ # memoize_delegate :min, to: :@@class_array
69
+ # memoize_delegate :max, to: :@instance_array
70
+ # end
71
+ #
72
+ # Foo.new.sum # => 6
73
+ # Foo.new.min # => 4
74
+ # Foo.new.max # => 11
75
+ #
76
+ # It's also possible to memoize_delegate a method to the class by using +:class+:
77
+ #
78
+ # class Foo
79
+ # def self.hello
80
+ # "world"
81
+ # end
82
+ #
83
+ # memoize_delegate :hello, to: :class
84
+ # end
85
+ #
86
+ # Foo.new.hello # => "world"
87
+ #
88
+ # Delegates can optionally be prefixed using the <tt>:prefix</tt> option. If the value
89
+ # is <tt>true</tt>, the memoize_delegate methods are prefixed with the name of the object being
90
+ # memoize_delegated to.
91
+ #
92
+ # Person = Struct.new(:name, :address)
93
+ #
94
+ # class Invoice < Struct.new(:client)
95
+ # memoize_delegate :name, :address, to: :client, prefix: true
96
+ # end
97
+ #
98
+ # john_doe = Person.new('John Doe', 'Vimmersvej 13')
99
+ # invoice = Invoice.new(john_doe)
100
+ # invoice.client_name # => "John Doe"
101
+ # invoice.client_address # => "Vimmersvej 13"
102
+ #
103
+ # It is also possible to supply a custom prefix.
104
+ #
105
+ # class Invoice < Struct.new(:client)
106
+ # memoize_delegate :name, :address, to: :client, prefix: :customer
107
+ # end
108
+ #
109
+ # invoice = Invoice.new(john_doe)
110
+ # invoice.customer_name # => 'John Doe'
111
+ # invoice.customer_address # => 'Vimmersvej 13'
112
+ #
113
+ # If the target is +nil+ and does not respond to the memoize_delegated method a
114
+ # +NoMethodError+ is raised, as with any other value. Sometimes, however, it
115
+ # makes sense to be robust to that situation and that is the purpose of the
116
+ # <tt>:allow_nil</tt> option: If the target is not +nil+, or it is and
117
+ # responds to the method, everything works as usual. But if it is +nil+ and
118
+ # does not respond to the memoize_delegated method, +nil+ is returned.
119
+ #
120
+ # class User < ActiveRecord::Base
121
+ # has_one :profile
122
+ # memoize_delegate :age, to: :profile
123
+ # end
124
+ #
125
+ # User.new.age # raises NoMethodError: undefined method `age'
126
+ #
127
+ # But if not having a profile yet is fine and should not be an error
128
+ # condition:
129
+ #
130
+ # class User < ActiveRecord::Base
131
+ # has_one :profile
132
+ # memoize_delegate :age, to: :profile, allow_nil: true
133
+ # end
134
+ #
135
+ # User.new.age # nil
136
+ #
137
+ # Note that if the target is not +nil+ then the call is attempted regardless of the
138
+ # <tt>:allow_nil</tt> option, and thus an exception is still raised if said object
139
+ # does not respond to the method:
140
+ #
141
+ # class Foo
142
+ # def initialize(bar)
143
+ # @bar = bar
144
+ # end
145
+ #
146
+ # memoize_delegate :name, to: :@bar, allow_nil: true
147
+ # end
148
+ #
149
+ # Foo.new("Bar").name # raises NoMethodError: undefined method `name'
150
+ #
151
+ # The target method must be public, otherwise it will raise +NoMethodError+.
152
+ #
153
+ def memoize_delegate(*methods, to: nil, prefix: nil, allow_nil: nil)
154
+ unless to
155
+ raise ArgumentError, 'Delegation needs a target. Supply an options hash with a :to key as the last argument (e.g. memoize_delegate :hello, to: :greeter).'
156
+ end
157
+
158
+ if prefix == true && to =~ /^[^a-z_]/
159
+ raise ArgumentError, 'Can only automatically set the delegation prefix when delegating to a method.'
160
+ end
161
+
162
+ method_prefix = \
163
+ if prefix
164
+ "#{prefix == true ? to : prefix}_"
165
+ else
166
+ ''
167
+ end
168
+
169
+ location = caller_locations(1, 1).first
170
+ file, line = location.path, location.lineno
171
+
172
+ to = to.to_s
173
+ to = "self.#{to}" if DELEGATION_RESERVED_METHOD_NAMES.include?(to)
174
+
175
+ methods.each do |method|
176
+ # Attribute writer methods only accept one argument. Makes sure []=
177
+ # methods still accept two arguments.
178
+ definition = (method =~ /[^\]]=$/) ? 'arg' : '*args, &block'
179
+
180
+ # The following generated method calls the target exactly once, storing
181
+ # the returned value in a dummy variable.
182
+ #
183
+ # Reason is twofold: On one hand doing less calls is in general better.
184
+ # On the other hand it could be that the target has side-effects,
185
+ # whereas conceptually, from the user point of view, the delegator should
186
+ # be doing one call.
187
+ if allow_nil
188
+ method_def = [
189
+ "def #{method_prefix}#{method}(#{definition})",
190
+ "_ = #{to}",
191
+ "if !_.nil? || nil.respond_to?(:#{method})",
192
+ " if instance_variable_get('@_memoize_delegate_#{to}_#{method}')",
193
+ " instance_variable_get('@_memoize_delegate_#{to}_#{method}')",
194
+ " else",
195
+ " instance_variable_set('@_memoize_delegate_#{to}_#{method}', _.#{method}(#{definition}))",
196
+ " end",
197
+ "end",
198
+ "end"
199
+ ].join ';'
200
+ else
201
+ exception = %(raise DelegationError, "#{self}##{method_prefix}#{method} memoize_delegated to #{to}.#{method}, but #{to} is nil: \#{self.inspect}")
202
+
203
+ method_def = [
204
+ "def #{method_prefix}#{method}(#{definition})",
205
+ " _ = #{to}",
206
+ " if instance_variable_get('@_memoize_delegate_#{to}_#{method}')",
207
+ " instance_variable_get('@_memoize_delegate_#{to}_#{method}')",
208
+ " else",
209
+ " instance_variable_set('@_memoize_delegate_#{to}_#{method}', _.#{method}(#{definition}))",
210
+ " end",
211
+ "rescue NoMethodError => e",
212
+ " if _.nil? && e.name == :#{method}",
213
+ " #{exception}",
214
+ " else",
215
+ " raise",
216
+ " end",
217
+ "end"
218
+ ].join ';'
219
+ end
220
+
221
+ module_eval(method_def, file, line)
222
+ end
223
+ end
224
+ end
@@ -0,0 +1,3 @@
1
+ module MemoizeDelegate
2
+ VERSION = "0.1.0"
3
+ end
@@ -0,0 +1,27 @@
1
+ # coding: utf-8
2
+ lib = File.expand_path('../lib', __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require 'memoize_delegate/version'
5
+
6
+ Gem::Specification.new do |spec|
7
+ spec.name = "memoize_delegate"
8
+ spec.version = MemoizeDelegate::VERSION
9
+ spec.authors = ["Mathieu Jobin"]
10
+ spec.email = ["mathieu@justbudget.com"]
11
+
12
+ spec.summary = %q{Similar to ruby delegate class method, but memoize the result.}
13
+ spec.description = spec.summary
14
+ spec.homepage = "https://github.com/mathieujobin/memoize_delegate"
15
+ spec.license = "MIT"
16
+
17
+ spec.files = `git ls-files -z`.split("\x0").reject do |f|
18
+ f.match(%r{^(test|spec|features)/})
19
+ end
20
+ spec.bindir = "exe"
21
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
22
+ spec.require_paths = ["lib"]
23
+
24
+ spec.add_development_dependency "bundler", "~> 1.14"
25
+ spec.add_development_dependency "rake", "~> 10.0"
26
+ spec.add_development_dependency "rspec", "~> 3.0"
27
+ end
metadata ADDED
@@ -0,0 +1,100 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: memoize_delegate
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Mathieu Jobin
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2017-05-30 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: bundler
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: '1.14'
20
+ type: :development
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '1.14'
27
+ - !ruby/object:Gem::Dependency
28
+ name: rake
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: '10.0'
34
+ type: :development
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: '10.0'
41
+ - !ruby/object:Gem::Dependency
42
+ name: rspec
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - "~>"
46
+ - !ruby/object:Gem::Version
47
+ version: '3.0'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - "~>"
53
+ - !ruby/object:Gem::Version
54
+ version: '3.0'
55
+ description: Similar to ruby delegate class method, but memoize the result.
56
+ email:
57
+ - mathieu@justbudget.com
58
+ executables: []
59
+ extensions: []
60
+ extra_rdoc_files: []
61
+ files:
62
+ - ".gitignore"
63
+ - ".rspec"
64
+ - ".travis.yml"
65
+ - CODE_OF_CONDUCT.md
66
+ - Gemfile
67
+ - LICENSE.txt
68
+ - README.md
69
+ - Rakefile
70
+ - bin/console
71
+ - bin/setup
72
+ - lib/memoize_delegate.rb
73
+ - lib/memoize_delegate/delegation.rb
74
+ - lib/memoize_delegate/version.rb
75
+ - memoize_delegate.gemspec
76
+ homepage: https://github.com/mathieujobin/memoize_delegate
77
+ licenses:
78
+ - MIT
79
+ metadata: {}
80
+ post_install_message:
81
+ rdoc_options: []
82
+ require_paths:
83
+ - lib
84
+ required_ruby_version: !ruby/object:Gem::Requirement
85
+ requirements:
86
+ - - ">="
87
+ - !ruby/object:Gem::Version
88
+ version: '0'
89
+ required_rubygems_version: !ruby/object:Gem::Requirement
90
+ requirements:
91
+ - - ">="
92
+ - !ruby/object:Gem::Version
93
+ version: '0'
94
+ requirements: []
95
+ rubyforge_project:
96
+ rubygems_version: 2.6.11
97
+ signing_key:
98
+ specification_version: 4
99
+ summary: Similar to ruby delegate class method, but memoize the result.
100
+ test_files: []