Skip to content

Commit

Permalink
Add ability preserve parameters definitions when subclassing
Browse files Browse the repository at this point in the history
  • Loading branch information
piotrmurach committed May 4, 2020
1 parent ef58080 commit cb497a7
Show file tree
Hide file tree
Showing 2 changed files with 68 additions and 0 deletions.
11 changes: 11 additions & 0 deletions lib/tty/option.rb
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,17 @@ def self.included(base)
base.module_eval do
include Interface
extend DSL
extend Inheritance
end
end

module Inheritance
# When class is inherited copy over parameter definitions
# This allows for definition of global parameters without
# affecting child class parameters and vice versa.
def inherited(subclass)
subclass.instance_variable_set(:@parameters, @parameters.dup)
super
end
end

Expand Down
57 changes: 57 additions & 0 deletions spec/unit/subclass_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
# frozen_string_literal: true

RSpec.describe TTY::Option do
it "inherits parameters from parent class" do
parent_class = command("ParentCmd") do
option :foo do
long "--foo string"
end
end

child_class = command("ChildCmd", parent_class)

expect(parent_class.parameters.map(&:name))
.to eq(child_class.parameters.map(&:name))

parent_cmd = parent_class.new
child_cmd = child_class.new

child_cmd.parse(%w[--foo b])
parent_cmd.parse(%w[--foo a])

expect(parent_cmd.params[:foo]).to eq("a")
expect(parent_cmd.remaining).to eq([])
expect(child_cmd.params[:foo]).to eq("b")
expect(child_cmd.remaining).to eq([])
end

it "adds new parameters in child class" do
parent_class = command("ParentCmd") do
option :foo do
long "--foo string"
end
end

child_class = command("ChildCmd", parent_class) do
option :bar do
long "--bar string"
end
end

parent_cmd = parent_class.new
child_cmd = child_class.new

child_cmd.parse(%w[--foo a --bar b])
parent_cmd.parse(%w[--foo a --bar b], check_invalid_params: false)

expect(parent_class.parameters.map(&:name)).to eq([:foo])
expect(parent_cmd.params[:foo]).to eq("a")
expect(parent_cmd.params[:bar]).to eq(nil)
expect(parent_cmd.remaining).to eq(%w[--bar b])

expect(child_class.parameters.map(&:name)).to eq([:foo, :bar])
expect(child_cmd.params[:foo]).to eq("a")
expect(child_cmd.params[:bar]).to eq("b")
expect(child_cmd.remaining).to eq([])
end
end

0 comments on commit cb497a7

Please sign in to comment.