Skip to content

Commit 5b754c8

Browse files
committed
Implemented Record.__record__(:index) syntax, Issue 1414.
1 parent d195429 commit 5b754c8

File tree

2 files changed

+28
-1
lines changed

2 files changed

+28
-1
lines changed

lib/elixir/lib/record.ex

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -573,7 +573,7 @@ defmodule Record do
573573
## Function generation
574574
575575
# Define __record__/1 and __record__/2 as reflection functions
576-
# that returns the record names and fields.
576+
# that return the record names and fields.
577577
#
578578
# Note that fields are *not* keywords. They are in the same
579579
# order as given as parameter and reflects the order of the
@@ -585,9 +585,26 @@ defmodule Record do
585585
#
586586
# FileInfo.__record__(:name) #=> FileInfo
587587
# FileInfo.__record__(:fields) #=> [atime: nil, mtime: nil]
588+
# FileInfo.__record__(:index, :atime) #=> 1
589+
# FileInfo.__record__(:index, :mtime) #=> 2
588590
#
589591
defp reflection(values) do
592+
quoted = lc { k, _ } inlist values do
593+
index = find_index(values, k, 0)
594+
quote do
595+
@doc false
596+
def __record__(:index, unquote(k)), do: unquote(index + 1)
597+
end
598+
end
599+
590600
quote do
601+
unquote(quoted)
602+
603+
@doc false
604+
def __record__(:index, _), do: nil
605+
@doc false
606+
def __record__(:index, arg, _), do: __record__(:index, arg)
607+
591608
@doc false
592609
def __record__(kind, _), do: __record__(kind)
593610

lib/elixir/test/elixir/record_test.exs

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -126,6 +126,16 @@ defmodule RecordTest do
126126
assert RecordTest.FileInfo.__index__(:atime) == record.__index__(:atime)
127127
end
128128

129+
test :__record_index__ do
130+
record = RecordTest.DynamicName.new(a: "a", b: "b")
131+
assert record.__record__(:index, :a) == 1
132+
assert elem(record, record.__record__(:index, :a)) == "a"
133+
assert elem(record, record.__record__(:index, :b)) == "b"
134+
assert record.__record__(:index, :c) == nil
135+
record = RecordTest.FileInfo.new
136+
assert RecordTest.FileInfo.__record__(:index, :atime) == record.__record__(:index, :atime)
137+
end
138+
129139
test :to_keywords do
130140
record = RecordTest.DynamicName.new(a: "a", b: "b")
131141
assert record.to_keywords[:a] == "a"

0 commit comments

Comments
 (0)