Runtime assertions for Ruby literal.fun
ruby
5
fork

Configure Feed

Select the types of activity you want to include in your feed.

Implement Literal::Data.define (#335)

Proposal:

It would be nice to have a `define` like the [native Data
structure](https://docs.ruby-lang.org/en/master/Data.html). It is useful
for code like this:

```ruby
# Before
class CreateUser
Success = Class.new(Literal::Data) do
prop :user, User
end

Failure = Class.new(Literal::Data) do
prop :reason, Symbol
prop :user, User
end
end

# After
class CreateUser
Success = Literal::Data.define(user: User)
Failure = Literal::Data.define(reason: Symbol, user: User)
end
```

With this define, we lose the ability to specify kind, reader,
predicate, and default values, but I believe the goal is to provide a
straightforward way to define simple data structures.

Co-authored-by: Joel Drapper <joel@drapper.me>

authored by

stephann
Joel Drapper
and committed by
GitHub
ef5cc3ca e0b819bd

+14
+7
lib/literal/data.rb
··· 2 2 3 3 class Literal::Data < Literal::DataStructure 4 4 class << self 5 + 6 + def define(**properties) 7 + Class.new(self) do 8 + properties.each { |name, type| prop(name, type) } 9 + end 10 + end 11 + 5 12 def [](...) = new(...) 6 13 7 14 def prop(name, type, kind = :keyword, reader: :public, predicate: false, default: nil)
+7
test/data.test.rb
··· 83 83 assert_equal(empty.hash != other_empty.hash, true) 84 84 end 85 85 86 + test "define" do 87 + person_with_define = Literal::Data.define(name: String).new(name: "John") 88 + person = Person.new(name: "John") 89 + 90 + assert_equal(person_with_define.to_h, person.to_h) 91 + end 92 + 86 93 test "initialize with [] method" do 87 94 person_a = Person.new(name: "John") 88 95 person_b = Person[name: "John"]