dataclass
case_class
Case class macros for the Crystal Language.
Installation
Add this to your application's shard.yml
:
dependencies:
case_class:
github: lbarasti/case_class
Usage
require "case_class"
Defining a class with read-only fields is as easy as
case_class Person{name : String, age : Int = 18}
Case classes also define a human readable string representation for the class
p = Person.new("Rick", 28)
puts p # prints "Person(Rick, 28)"
If you're into ADTs, then you will enjoy case_class
support for inheritance. Here is a sample implementation for a calculator data types.
abstract class Expr(T)
end
case_class IntExpr{value : Int32} < Expr(Int32)
case_class BoolExpr{value : Bool} < Expr(Bool)
case_class Add{a : Expr(Int32), b : Expr(Int32)} < Expr(Int32)
case_class Eq{a : Expr(Int32), b : Expr(Int32)} < Expr(Bool)
Known Limitations
- case_class definition must have at least one argument. This is by design. Use
class NoArgClass; end
instead. - case_class definitions are body-free. If you want to define additonal methods on a case class, then just re-open the definition:
case_class YourClass{id : String}
class YourClass
# additional methods here
end
Development
To expand the macro
crystal tool expand -c <path/to/file.cr>:<line>:<col> <path/to/file.cr>
Contributing
- Fork it ( https://github.com/lbarasti/case_class/fork )
- Create your feature branch (git checkout -b my-new-feature)
- Commit your changes (git commit -am 'Add some feature')
- Push to the branch (git push origin my-new-feature)
- Create a new Pull Request
Contributors
- lbarasti - creator, maintainer