Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion lib/literal/data.rb
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,13 @@ class Literal::Data < Literal::DataStructure
class << self
def [](...) = new(...)

def define(**properties)
def define(**properties, &body)
Class.new(self) do
properties.each { |name, type| prop(name, type) }

if block_given?
class_exec(&body)
end
end
end

Expand Down
13 changes: 13 additions & 0 deletions test/data.test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,19 @@ class ReaderlessExample < Literal::Data
assert_equal(person_with_define.to_h, person.to_h)
end

test "define block" do
Rect = Literal::Data.define(w: Integer, h: Integer) do
prop :filled, _Boolean, default: false, predicate: :public

def area = @w * @h
end

rect = Rect[w: 5, h: 4, filled: true]

assert_equal(rect.area, 20)
assert rect.filled?
end

test "initialize with [] method" do
person_a = Person.new(name: "John")
person_b = Person[name: "John"]
Expand Down
Loading