Skip to content

Commit

Permalink
Include keyword arguments in AST
Browse files Browse the repository at this point in the history
This means the kwargs are always present in the AST, thus updating all the expected responses.
  • Loading branch information
pat committed Mar 10, 2021
1 parent 15ecd98 commit 718b299
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 14 deletions.
19 changes: 17 additions & 2 deletions lib/dry/transformer/function.rb
Original file line number Diff line number Diff line change
Expand Up @@ -97,8 +97,7 @@ def ==(other)
#
# @api public
def to_ast
args_ast = args.map { |arg| arg.respond_to?(:to_ast) ? arg.to_ast : arg }
[name, args_ast]
[name, object_to_ast(args), object_to_ast(kwargs)]
end

# Converts a transproc to a simple proc
Expand All @@ -112,6 +111,22 @@ def to_proc
fn.to_proc
end
end

private

# @api private
def object_to_ast(object)
case object
when Array
object.map { |item| object_to_ast(item) }
when Hash
object.each_with_object({}) { |(key, value), hash|
hash[object_to_ast(key)] = object_to_ast(value)
}
else
object.respond_to?(:to_ast) ? object.to_ast : object
end
end
end
end
end
40 changes: 28 additions & 12 deletions spec/unit/function_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -34,9 +34,9 @@

expect(f3.to_ast).to eql(
[
:symbolize_keys, [],
:symbolize_keys, [], {},
[
:rename_keys, [user_name: :name]
:rename_keys, [], {user_name: :name}
]
]
)
Expand All @@ -47,12 +47,12 @@

expect(f4.to_ast).to eql(
[
:symbolize_keys, [],
:symbolize_keys, [], {},
[
:rename_keys, [user_name: :name]
:rename_keys, [], {user_name: :name}
],
[
:nest, [:details, [:name]]
:nest, [:details, [:name]], {}
]
]
)
Expand All @@ -68,9 +68,9 @@

expect(f3.to_ast).to eql(
[
f1.fn, [2],
f1.fn, [2], {},
[
f2.fn, []
f2.fn, [], {}
]
]
)
Expand All @@ -83,9 +83,9 @@
expect(f["user_name" => "Jane"]).to eql(name: "Jane")
expect(f.to_ast).to eql(
[
:symbolize_keys, [],
:symbolize_keys, [], {},
[
:rename_keys, [user_name: :name]
:rename_keys, [], {user_name: :name}
]
]
)
Expand All @@ -96,7 +96,7 @@
fn = container.t(:to_string)

expect(fn[:ok]).to eql("ok")
expect(fn.to_ast).to eql([:to_string, []])
expect(fn.to_ast).to eql([:to_string, [], {}])
end

it "plays well with functions as arguments" do
Expand All @@ -108,11 +108,27 @@
expect(fn.to_ast).to eql(
[
:map_array, [
[:to_symbol, []]
]
[:to_symbol, [], {}]
], {}
]
)
end

it "plays well with keyword arguments" do
container = Module.new do
extend Dry::Transformer::Registry

def self.trim(string, limit:)
string[0..(limit - 1)]
end
end

fn = container[:trim, limit: 3]

expect(fn.to_ast).to eql(
[:trim, [], {limit: 3}]
)
end
end

describe "#==" do
Expand Down

0 comments on commit 718b299

Please sign in to comment.