Skip to content

Commit

Permalink
refactor(entry): delegate to instance method under the hood
Browse files Browse the repository at this point in the history
  • Loading branch information
marian13 committed Dec 4, 2023
1 parent 0fa22b1 commit 521d685
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 7 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,15 @@ def initialize(feature_class:, name:, body:)
# @return [String, Symbol]
#
def call
feature_class.define_singleton_method(name, &body)
##
# NOTE: Just `feature_class.define_singleton_method` does NOT create a closure for `name`.
# That is why `feature_class.class_exec` wrapper is required.
#
feature_class.class_exec(name) do |name|
define_singleton_method(name) { |*args, **kwargs, &block| new.public_send(name, *args, **kwargs, &block) }
end

feature_class.define_method(name, &body)

name
end
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@
end
end

let(:feature_instance) { feature_class.new }

let(:name) { :foo }
let(:body) { proc { |*args, **kwargs, &block| [__method__, args, kwargs, block] } }

Expand All @@ -33,13 +35,21 @@
expect { command_result }.to change { feature_class.methods(false).include?(name.to_sym) }.from(false).to(true)
end

it "defines instance method with `name` on `feature_class`" do
##
# NOTE: `false` in `instance_methods(false)` means own methods.
# - https://ruby-doc.org/core-2.7.0/Object.html#method-i-methods
#
expect { command_result }.to change { feature_class.instance_methods(false).include?(name.to_sym) }.from(false).to(true)
end

context "when class method with `name` on `feature_class` already exist" do
let(:feature_class) do
Module.new do
class << self
def foo
:foo
end
Class.new do
include ConvenientService::Feature::Configs::Standard

def self.foo
:foo
end
end
end
Expand All @@ -51,7 +61,25 @@ def foo
end
end

example_group "generated method" do
context "when instance method with `name` on `feature_class` already exist" do
let(:feature_class) do
Class.new do
include ConvenientService::Feature::Configs::Standard

def foo
:foo
end
end
end

it "overrides that already existing instance method" do
command_result

expect(feature_instance.foo).to eq([name, [], {}, nil])
end
end

example_group "generated class method" do
it "returns `body` value" do
command_result

Expand All @@ -70,6 +98,26 @@ def foo
end
end
end

example_group "generated instance method" do
it "returns `body` value" do
command_result

expect(feature_instance.foo).to eq([name, [], {}, nil])
end

context "when `body` accepts arguments" do
let(:args) { [:foo] }
let(:kwargs) { {foo: :bar} }
let(:block) { proc { :foo } }

it "accepts same arguments as `body`" do
command_result

expect(feature_instance.foo(*args, **kwargs, &block)).to eq([name, args, kwargs, block])
end
end
end
end
end
end
Expand Down

0 comments on commit 521d685

Please sign in to comment.