Skip to content

Commit

Permalink
Add copy method to record macro. (#5736)
Browse files Browse the repository at this point in the history
* Add copy method to record macro.

This allows a copy of a record to be made, specifying
only the properties that should be changed.

* Format macros source.

* Rename `copy` to `copy_with`.

* Improve record documentation.
  • Loading branch information
chris-baynes authored and RX14 committed Jun 12, 2018
1 parent d9b024e commit 0a898dd
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 0 deletions.
12 changes: 12 additions & 0 deletions spec/std/record_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,10 @@ describe "record" do
rec.x.should eq(1)
rec.y.should be(ary)

copy = rec.copy_with(x: 5)
copy.x.should eq(5)
copy.y.should be(rec.y)

cloned = rec.clone
cloned.x.should eq(1)
cloned.y.should eq(ary)
Expand All @@ -32,6 +36,10 @@ describe "record" do
rec.x.should eq(0)
rec.y.should eq([2, 3])

copy = rec.copy_with(y: [7, 8])
copy.x.should eq(rec.x)
copy.y.should eq([7, 8])

cloned = rec.clone
cloned.x.should eq(0)
cloned.y.should eq(rec.y)
Expand All @@ -43,6 +51,10 @@ describe "record" do
rec.x.should eq(0)
rec.y.should eq([2, 3])

copy = rec.copy_with(y: [7, 8])
copy.x.should eq(rec.x)
copy.y.should eq([7, 8])

cloned = rec.clone
cloned.x.should eq(0)
cloned.y.should eq(rec.y)
Expand Down
35 changes: 35 additions & 0 deletions src/macros.cr
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,17 @@
# Point.new # => #<Point(@x=0, @y=0)>
# Point.new y: 2 # => #<Point(@x=0, @y=2)>
# ```
#
# This macro also provides a `copy_with` method which returns
# a copy of the record with the provided properties altered.
#
# ```
# record Point, x = 0, y = 0
#
# p = Point.new y: 2 # => #<Point(@x=0, @y=2)>
# p.copy_with x: 3 # => #<Point(@x=3, @y=2)>
# p # => #<Point(@x=0, @y=2)>
# ```
macro record(name, *properties)
struct {{name.id}}
{% for property in properties %}
Expand All @@ -67,6 +78,30 @@ macro record(name, *properties)

{{yield}}

def copy_with({{
*properties.map do |property|
if property.is_a?(Assign)
"#{property.target.id} _#{property.target.id} = @#{property.target.id}".id
elsif property.is_a?(TypeDeclaration)
"#{property.var.id} _#{property.var.id} = @#{property.var.id}".id
else
"#{property.id} _#{property.id} = @#{property.id}".id
end
end
}})
{{name.id}}.new({{
*properties.map do |property|
if property.is_a?(Assign)
"_#{property.target.id}".id
elsif property.is_a?(TypeDeclaration)
"_#{property.var.id}".id
else
"_#{property.id}".id
end
end
}})
end

def clone
{{name.id}}.new({{
*properties.map do |property|
Expand Down

0 comments on commit 0a898dd

Please sign in to comment.