generate_method 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: e1aecfbdbc29d8cf9e86453a1a39971ecd6411ae
4
+ data.tar.gz: 861f1c8d360a396f8eceb66536d227929843ce2a
5
+ SHA512:
6
+ metadata.gz: 424546393cb2758fba26e81e4ca3cca9341d0f6d146de388a258194fadcb0a18d38b89c777d8978392c9dbcc8f2df0b34b4bc2e0a773368377a085d7f9640407
7
+ data.tar.gz: c807adb7103e542da8efa14af06cbe4414b27b3e758108b1d1b583ae64791198f40b338fa8d8e1bfefb5861279fde50b6b60354dc8c5cf2f1f33d55ccfe87c68
@@ -0,0 +1,14 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /Gemfile.lock
4
+ /_yardoc/
5
+ /coverage/
6
+ /doc/
7
+ /pkg/
8
+ /spec/reports/
9
+ /tmp/
10
+ *.bundle
11
+ *.so
12
+ *.o
13
+ *.a
14
+ mkmf.log
data/.rspec ADDED
@@ -0,0 +1,2 @@
1
+ --color
2
+ --require spec_helper
data/Gemfile ADDED
@@ -0,0 +1,4 @@
1
+ source 'https://rubygems.org'
2
+
3
+ # Specify your gem's dependencies in generate_method.gemspec
4
+ gemspec
@@ -0,0 +1,141 @@
1
+ # generate_method [![Gem Version](https://badge.fury.io/rb/generate_method.svg)](http://badge.fury.io/rb/generate_method)
2
+
3
+ Nicely generate methods on a Class or Module, by using module inclusion
4
+ (inheritence) - allowing your gem's users to override your generated methods
5
+ nicely.
6
+
7
+ ## Installation
8
+
9
+ Add this line to your application's Gemfile:
10
+
11
+ ```ruby
12
+ gem 'generate_method'
13
+ ```
14
+
15
+ And then execute:
16
+
17
+ $ bundle
18
+
19
+ Or install it yourself as:
20
+
21
+ $ gem install generate_method
22
+
23
+ ## Usage
24
+
25
+ Your gem has a simple method that generates methods on your users' `Module`.
26
+
27
+ You would usually do it like this:
28
+
29
+ ```ruby
30
+ class Module
31
+ def attr_reader(name)
32
+ define_method(name) do
33
+ instance_variable_get("@#{name}")
34
+ end
35
+ end
36
+ end
37
+ ```
38
+
39
+ From now on, will be revised like this:
40
+
41
+ ```ruby
42
+ class Module
43
+ # When the method's name is dynamic:
44
+ def attr_reader(name)
45
+ generate_method(name) do
46
+ instance_variable_get("@#{name}")
47
+ end
48
+ end
49
+ # When the method's name is fixed:
50
+ # (also more efficient when generating multiple methods)
51
+ def create_reader
52
+ generate_methods do
53
+ def reader
54
+ @reader
55
+ end
56
+ end
57
+ end
58
+ end
59
+ ```
60
+
61
+ By using one of the above syntax, a few problems will be solved:
62
+
63
+ ### Ancestors stack
64
+
65
+ When using `generate_methods` the generated methods will be added to the
66
+ ancestors stack, so if your gem's user decides to override your method and call
67
+ `super` to get your implementation. The original 'bad' implementation will not
68
+ allow it because `define_method` will implement on the base class's level and
69
+ therefore re-implementing it will not allow calling `super` on the same level.
70
+
71
+ ```ruby
72
+ class MyClass
73
+ attr_reader :x
74
+ def x
75
+ super.to_i
76
+ end
77
+ end
78
+ instance = MyClass.new(x: "123")
79
+ instance.x
80
+ => 123
81
+ ```
82
+
83
+ ### Overriding existing methods
84
+
85
+ You can add `overrider: <overrider_name>` option to the `generate_method` call. This will
86
+ cause existing methods in the class to be aliased into
87
+ `<method_name>_without_<overrider_name>` (pushing ?/!,= to the end of the
88
+ method name). That way you can easily call the overriden method in your
89
+ generated method.
90
+
91
+ ```ruby
92
+ class Module
93
+ def increment_attr(name)
94
+ generate_method(name, overrider: :increment) do
95
+ send(:"#{name}_without_increment") + 1
96
+ end
97
+ end
98
+ end
99
+ ```
100
+
101
+ Sometimes the method is implemented in `method_missing` of the parent (like
102
+ with ActiveRecord 4.1 columns), and so `alias_method` will not really work. In that
103
+ case you might want to implement your generated method like so:
104
+
105
+ ```ruby
106
+ (respond_to?(:"#{name}_without_increment") ? send(:"#{name}_without_increment") : super()) + 1
107
+ ```
108
+
109
+ In `super()`, the `()` are not needed if you use the `generate_methods`
110
+ (plural) syntax, your arguments will automatically be passed to the parent.
111
+
112
+ Your user will also be able to override the underlying method like so:
113
+
114
+ ```ruby
115
+ class MyClass
116
+ attr_accessor :x
117
+ increment_attr :x
118
+
119
+ def x_without_increment
120
+ super.to_i
121
+ end
122
+ end
123
+
124
+ instance = MyClass.new
125
+ instance.x = "123"
126
+ instance.x
127
+ => 124
128
+ ```
129
+
130
+ `super` will call the original implementation (the one created by
131
+ `attr_accessor`). If you know that implementation, you can skip calling super
132
+ (and use `@x`). If you don't know the implementation (like with ActiveRecord),
133
+ you will probably want to call `super`.
134
+
135
+ ## Contributing
136
+
137
+ 1. Fork it ( https://github.com/odedniv/generate_method/fork )
138
+ 2. Create your feature branch (`git checkout -b my-new-feature`)
139
+ 3. Commit your changes (`git commit -am 'Add some feature'`)
140
+ 4. Push to the branch (`git push origin my-new-feature`)
141
+ 5. Create a new Pull Request
@@ -0,0 +1,2 @@
1
+ require "bundler/gem_tasks"
2
+
@@ -0,0 +1,24 @@
1
+ This is free and unencumbered software released into the public domain.
2
+
3
+ Anyone is free to copy, modify, publish, use, compile, sell, or
4
+ distribute this software, either in source code form or as a compiled
5
+ binary, for any purpose, commercial or non-commercial, and by any
6
+ means.
7
+
8
+ In jurisdictions that recognize copyright laws, the author or authors
9
+ of this software dedicate any and all copyright interest in the
10
+ software to the public domain. We make this dedication for the benefit
11
+ of the public at large and to the detriment of our heirs and
12
+ successors. We intend this dedication to be an overt act of
13
+ relinquishment in perpetuity of all present and future rights to this
14
+ software under copyright law.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
19
+ IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
20
+ OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
21
+ ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
22
+ OTHER DEALINGS IN THE SOFTWARE.
23
+
24
+ For more information, please refer to <http://unlicense.org/>
@@ -0,0 +1,23 @@
1
+ # coding: utf-8
2
+ lib = File.expand_path('../lib', __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require 'generate_method/version'
5
+
6
+ Gem::Specification.new do |spec|
7
+ spec.name = "generate_method"
8
+ spec.version = GenerateMethod::VERSION
9
+ spec.authors = ["Oded Niv"]
10
+ spec.email = ["oded.niv@gmail.com"]
11
+ spec.summary = %q{Nicely generate methods on a Class or Module.}
12
+ spec.description = %q{Allow your gem users to override your generated methods nicely.}
13
+ spec.homepage = "https://github.com/odedniv/generate_method"
14
+ spec.license = "UNLICENSE"
15
+
16
+ spec.files = `git ls-files -z`.split("\x0")
17
+ spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
18
+ spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
19
+ spec.require_paths = ["lib"]
20
+
21
+ spec.add_development_dependency "bundler", "~> 1.7"
22
+ spec.add_development_dependency "rspec", "~> 3.1"
23
+ end
@@ -0,0 +1,50 @@
1
+ require "generate_method/version"
2
+
3
+ module GenerateMethod
4
+ module Generator
5
+ def generate_method(method_name, overrider: nil, &block)
6
+ m = Module.new do
7
+ define_method(method_name, &block)
8
+ end
9
+ alias_generated_method(method_name, overrider: overrider, m: m)
10
+ include m
11
+ end
12
+
13
+ def generate_methods(overrider: nil, &block)
14
+ m = Module.new(&block)
15
+ m.instance_methods.each do |method_name|
16
+ alias_generated_method(method_name, overrider: overrider, m: m)
17
+ end
18
+ include m
19
+ end
20
+
21
+ private
22
+
23
+ def alias_generated_method(method_name, overrider: nil, m: nil)
24
+ return if overrider.nil?
25
+
26
+ method_name_s, override_name_s = method_name.to_s, overrider.to_s
27
+ # pushing one of [?=!] to the end of the _without_ method
28
+ if method_name_s =~ /[\=\?\!]$/
29
+ override_name_s.concat method_name_s[-1]
30
+ method_name_s.chop!
31
+ end
32
+ override_method_name = :"#{method_name_s}_without_#{override_name_s}"
33
+
34
+ begin
35
+ alias_method :"_#{override_method_name}", method_name
36
+ rescue NameError # method does not exist
37
+ else
38
+ m.instance_eval do
39
+ define_method(override_method_name) do |*args, &block|
40
+ send(:"_#{override_method_name}", *args, &block)
41
+ end
42
+ end
43
+ end
44
+ end
45
+ end
46
+ end
47
+
48
+ class Module
49
+ include GenerateMethod::Generator
50
+ end
@@ -0,0 +1,3 @@
1
+ module GenerateMethod
2
+ VERSION = "0.0.1"
3
+ end
@@ -0,0 +1,177 @@
1
+ require 'generate_method'
2
+
3
+ describe GenerateMethod::Generator do
4
+ subject(:instance) { klass.new }
5
+
6
+ describe "#generate_method" do
7
+ context "without overrider" do
8
+ let(:parent) do
9
+ Class.new do
10
+ def x?(a, b)
11
+ "parent#{a}#{b}#{yield}"
12
+ end
13
+ end
14
+ end
15
+ let(:klass) do
16
+ Class.new(parent) do
17
+ generate_method(:x?) { |a, b, &block| super(a, b, &block) + "-generated#{a}#{b}#{block.call}" }
18
+ def x?(a, b)
19
+ super + "-sub#{a}#{b}#{yield}"
20
+ end
21
+ end
22
+ end
23
+
24
+ it { should_not respond_to(:x_without_override?) }
25
+ specify { expect(instance.x?(1, 2) { '-block' }).to eq('parent12-block-generated12-block-sub12-block') }
26
+ end
27
+
28
+ context "with overrider" do
29
+ context "when supports alias" do
30
+ let(:klass) do
31
+ Class.new do
32
+ def x!(a, b)
33
+ "parent#{a}#{b}#{yield}"
34
+ end
35
+ generate_method(:x!, overrider: :override) { |a, b, &block| x_without_override!(a, b, &block) + "-generated#{a}#{b}#{block.call}" }
36
+ def x!(a, b)
37
+ super + "-sub#{a}#{b}#{yield}"
38
+ end
39
+ end
40
+ end
41
+
42
+ it { should respond_to(:x_without_override!) }
43
+ specify { expect(instance.x!(1, 2) { '-block' }).to eq('parent12-block-generated12-block-sub12-block') }
44
+ end
45
+
46
+ context "when does not support alias" do
47
+ let(:parent) do
48
+ Class.new do
49
+ def method_missing(method_name, *args, &block)
50
+ method_name == :x? ? "parent#{args.join}#{yield}" : super
51
+ end
52
+ end
53
+ end
54
+ let(:klass) do
55
+ Class.new(parent) do
56
+ generate_method(:x?, overrider: :override) { |a, b, &block| super(a, b, &block) + "-generated#{a}#{b}#{block.call}" }
57
+ def x?(a, b)
58
+ super + "-sub#{a}#{b}#{yield}"
59
+ end
60
+ end
61
+ end
62
+
63
+ it { should_not respond_to(:x_without_override?) }
64
+ specify { expect(instance.x?(1, 2) { '-block' }).to eq('parent12-block-generated12-block-sub12-block') }
65
+ end
66
+ end
67
+ end
68
+
69
+ describe "#generate_methods" do
70
+ context "without overrider" do
71
+ let(:parent) do
72
+ Class.new do
73
+ def x(a, b)
74
+ "parentx#{a}#{b}#{yield}"
75
+ end
76
+ def y(a, b)
77
+ "parenty#{a}#{b}#{yield}"
78
+ end
79
+ end
80
+ end
81
+ let(:klass) do
82
+ Class.new(parent) do
83
+ generate_methods do
84
+ def x(a, b)
85
+ super + "-generatedx#{a}#{b}#{yield}"
86
+ end
87
+ def y(a, b)
88
+ super + "-generatedy#{a}#{b}#{yield}"
89
+ end
90
+ end
91
+ def x(a, b)
92
+ super + "-subx#{a}#{b}#{yield}"
93
+ end
94
+ def y(a, b)
95
+ super + "-suby#{a}#{b}#{yield}"
96
+ end
97
+ end
98
+ end
99
+
100
+ it { should_not respond_to(:x_without_override) }
101
+ it { should_not respond_to(:y_without_override) }
102
+ specify { expect(instance.x(1, 2) { '-block' }).to eq('parentx12-block-generatedx12-block-subx12-block') }
103
+ specify { expect(instance.y(1, 2) { '-block' }).to eq('parenty12-block-generatedy12-block-suby12-block') }
104
+ end
105
+
106
+ context "with overrider" do
107
+ context "when supports alias" do
108
+ let(:klass) do
109
+ Class.new do
110
+ def x!(a, b)
111
+ "parentx#{a}#{b}#{yield}"
112
+ end
113
+ def y!(a, b)
114
+ "parenty#{a}#{b}#{yield}"
115
+ end
116
+ generate_methods(overrider: :override) do
117
+ def x!(a, b, &block)
118
+ x_without_override!(a, b, &block) + "-generatedx#{a}#{b}#{yield}"
119
+ end
120
+ def y!(a, b, &block)
121
+ y_without_override!(a, b, &block) + "-generatedy#{a}#{b}#{yield}"
122
+ end
123
+ end
124
+ def x!(a, b)
125
+ super + "-subx#{a}#{b}#{yield}"
126
+ end
127
+ def y!(a, b)
128
+ super + "-suby#{a}#{b}#{yield}"
129
+ end
130
+ end
131
+ end
132
+
133
+ it { should respond_to(:x_without_override!) }
134
+ it { should respond_to(:y_without_override!) }
135
+ specify { expect(instance.x!(1, 2) { '-block' }).to eq('parentx12-block-generatedx12-block-subx12-block') }
136
+ specify { expect(instance.y!(1, 2) { '-block' }).to eq('parenty12-block-generatedy12-block-suby12-block') }
137
+ end
138
+
139
+ context "when does not support alias" do
140
+ let(:parent) do
141
+ Class.new do
142
+ def method_missing(method_name, *args, &block)
143
+ case method_name
144
+ when :x? then "parentx#{args.join}#{yield}"
145
+ when :y? then "parenty#{args.join}#{yield}"
146
+ else super
147
+ end
148
+ end
149
+ end
150
+ end
151
+ let(:klass) do
152
+ Class.new(parent) do
153
+ generate_methods(overrider: :override) do
154
+ def x?(a, b, &block)
155
+ super(a, b, &block) + "-generatedx#{a}#{b}#{yield}"
156
+ end
157
+ def y?(a, b, &block)
158
+ super(a, b, &block) + "-generatedy#{a}#{b}#{yield}"
159
+ end
160
+ end
161
+ def x?(a, b)
162
+ super + "-subx#{a}#{b}#{yield}"
163
+ end
164
+ def y?(a, b)
165
+ super + "-suby#{a}#{b}#{yield}"
166
+ end
167
+ end
168
+ end
169
+
170
+ it { should_not respond_to(:x_without_override?) }
171
+ it { should_not respond_to(:y_without_override?) }
172
+ specify { expect(instance.x?(1, 2) { '-block' }).to eq('parentx12-block-generatedx12-block-subx12-block') }
173
+ specify { expect(instance.y?(1, 2) { '-block' }).to eq('parenty12-block-generatedy12-block-suby12-block') }
174
+ end
175
+ end
176
+ end
177
+ end
@@ -0,0 +1,89 @@
1
+ # This file was generated by the `rspec --init` command. Conventionally, all
2
+ # specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`.
3
+ # The generated `.rspec` file contains `--require spec_helper` which will cause this
4
+ # file to always be loaded, without a need to explicitly require it in any files.
5
+ #
6
+ # Given that it is always loaded, you are encouraged to keep this file as
7
+ # light-weight as possible. Requiring heavyweight dependencies from this file
8
+ # will add to the boot time of your test suite on EVERY test run, even for an
9
+ # individual file that may not need all of that loaded. Instead, consider making
10
+ # a separate helper file that requires the additional dependencies and performs
11
+ # the additional setup, and require it from the spec files that actually need it.
12
+ #
13
+ # The `.rspec` file also contains a few flags that are not defaults but that
14
+ # users commonly want.
15
+ #
16
+ # See http://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration
17
+ RSpec.configure do |config|
18
+ # rspec-expectations config goes here. You can use an alternate
19
+ # assertion/expectation library such as wrong or the stdlib/minitest
20
+ # assertions if you prefer.
21
+ config.expect_with :rspec do |expectations|
22
+ # This option will default to `true` in RSpec 4. It makes the `description`
23
+ # and `failure_message` of custom matchers include text for helper methods
24
+ # defined using `chain`, e.g.:
25
+ # be_bigger_than(2).and_smaller_than(4).description
26
+ # # => "be bigger than 2 and smaller than 4"
27
+ # ...rather than:
28
+ # # => "be bigger than 2"
29
+ expectations.include_chain_clauses_in_custom_matcher_descriptions = true
30
+ end
31
+
32
+ # rspec-mocks config goes here. You can use an alternate test double
33
+ # library (such as bogus or mocha) by changing the `mock_with` option here.
34
+ config.mock_with :rspec do |mocks|
35
+ # Prevents you from mocking or stubbing a method that does not exist on
36
+ # a real object. This is generally recommended, and will default to
37
+ # `true` in RSpec 4.
38
+ mocks.verify_partial_doubles = true
39
+ end
40
+
41
+ # The settings below are suggested to provide a good initial experience
42
+ # with RSpec, but feel free to customize to your heart's content.
43
+ =begin
44
+ # These two settings work together to allow you to limit a spec run
45
+ # to individual examples or groups you care about by tagging them with
46
+ # `:focus` metadata. When nothing is tagged with `:focus`, all examples
47
+ # get run.
48
+ config.filter_run :focus
49
+ config.run_all_when_everything_filtered = true
50
+
51
+ # Limits the available syntax to the non-monkey patched syntax that is recommended.
52
+ # For more details, see:
53
+ # - http://myronmars.to/n/dev-blog/2012/06/rspecs-new-expectation-syntax
54
+ # - http://teaisaweso.me/blog/2013/05/27/rspecs-new-message-expectation-syntax/
55
+ # - http://myronmars.to/n/dev-blog/2014/05/notable-changes-in-rspec-3#new__config_option_to_disable_rspeccore_monkey_patching
56
+ config.disable_monkey_patching!
57
+
58
+ # This setting enables warnings. It's recommended, but in some cases may
59
+ # be too noisy due to issues in dependencies.
60
+ config.warnings = true
61
+
62
+ # Many RSpec users commonly either run the entire suite or an individual
63
+ # file, and it's useful to allow more verbose output when running an
64
+ # individual spec file.
65
+ if config.files_to_run.one?
66
+ # Use the documentation formatter for detailed output,
67
+ # unless a formatter has already been configured
68
+ # (e.g. via a command-line flag).
69
+ config.default_formatter = 'doc'
70
+ end
71
+
72
+ # Print the 10 slowest examples and example groups at the
73
+ # end of the spec run, to help surface which specs are running
74
+ # particularly slow.
75
+ config.profile_examples = 10
76
+
77
+ # Run specs in random order to surface order dependencies. If you find an
78
+ # order dependency and want to debug it, you can fix the order by providing
79
+ # the seed, which is printed after each run.
80
+ # --seed 1234
81
+ config.order = :random
82
+
83
+ # Seed global randomization in this process using the `--seed` CLI option.
84
+ # Setting this allows you to use `--seed` to deterministically reproduce
85
+ # test failures related to randomization by passing the same `--seed` value
86
+ # as the one that triggered the failure.
87
+ Kernel.srand config.seed
88
+ =end
89
+ end
metadata ADDED
@@ -0,0 +1,85 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: generate_method
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.0.1
5
+ platform: ruby
6
+ authors:
7
+ - Oded Niv
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2014-11-17 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.7'
20
+ type: :development
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - ~>
25
+ - !ruby/object:Gem::Version
26
+ version: '1.7'
27
+ - !ruby/object:Gem::Dependency
28
+ name: rspec
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - ~>
32
+ - !ruby/object:Gem::Version
33
+ version: '3.1'
34
+ type: :development
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - ~>
39
+ - !ruby/object:Gem::Version
40
+ version: '3.1'
41
+ description: Allow your gem users to override your generated methods nicely.
42
+ email:
43
+ - oded.niv@gmail.com
44
+ executables: []
45
+ extensions: []
46
+ extra_rdoc_files: []
47
+ files:
48
+ - .gitignore
49
+ - .rspec
50
+ - Gemfile
51
+ - README.md
52
+ - Rakefile
53
+ - UNLICENSE
54
+ - generate_method.gemspec
55
+ - lib/generate_method.rb
56
+ - lib/generate_method/version.rb
57
+ - spec/generate_method_spec.rb
58
+ - spec/spec_helper.rb
59
+ homepage: https://github.com/odedniv/generate_method
60
+ licenses:
61
+ - UNLICENSE
62
+ metadata: {}
63
+ post_install_message:
64
+ rdoc_options: []
65
+ require_paths:
66
+ - lib
67
+ required_ruby_version: !ruby/object:Gem::Requirement
68
+ requirements:
69
+ - - '>='
70
+ - !ruby/object:Gem::Version
71
+ version: '0'
72
+ required_rubygems_version: !ruby/object:Gem::Requirement
73
+ requirements:
74
+ - - '>='
75
+ - !ruby/object:Gem::Version
76
+ version: '0'
77
+ requirements: []
78
+ rubyforge_project:
79
+ rubygems_version: 2.2.2
80
+ signing_key:
81
+ specification_version: 4
82
+ summary: Nicely generate methods on a Class or Module.
83
+ test_files:
84
+ - spec/generate_method_spec.rb
85
+ - spec/spec_helper.rb