Is it possible to make DSL in crystal?

313 views
Skip to first unread message

Grabli66 None

unread,
Sep 7, 2015, 9:02:55 AM9/7/15
to Crystal
Hi. I am trying to make some DLS in Crystal like this:

class Item2
  def initialize(&blk)
    instance_eval(&blk)
  end 
 
  def item2(&blk)
    Item2.new(&blk)
  end
 
  def test(s)
    puts "test"
  end
end

class Item1
  def initialize(&blk)
    instance_eval(&blk)
  end 
 
  def item2(&blk)
    Item2.new(&blk)
  end
end

def item1(&blk)
  Item1.new(&blk)
end

item1 {
  item2 {
    test("test")
  }
}

It works in Ruby. But Crystal compiler says that variable or method "item2" is undefined.
Where i am wrong?

Jonne Haß

unread,
Sep 7, 2015, 9:08:25 AM9/7/15
to crysta...@googlegroups.com
There's no instance_eval. There's a limited replacement though, with x yield. See http://carc.in/#/r/e2p

Another and probably greater avenue for building DSLs in Crystal is its macro system, three examples taking it quite far are artanis: https://github.com/ysbaddaden/artanis, the spec DSL of minitest.cr: https://github.com/ysbaddaden/minitest.cr/blob/master/src/minitest/spec.cr and spec2: https://github.com/waterlink/spec2.cr

Have fun!

- Jonne
> --
> You received this message because you are subscribed to the Google
> Groups "Crystal" group.
> To unsubscribe from this group and stop receiving emails from it, send
> an email to crystal-lang...@googlegroups.com
> <mailto:crystal-lang...@googlegroups.com>.
> To post to this group, send email to crysta...@googlegroups.com
> <mailto:crysta...@googlegroups.com>.
> Visit this group at http://groups.google.com/group/crystal-lang.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/crystal-lang/e60fd0a9-4668-4932-8b6f-07a7b81caf84%40googlegroups.com
> <https://groups.google.com/d/msgid/crystal-lang/e60fd0a9-4668-4932-8b6f-07a7b81caf84%40googlegroups.com?utm_medium=email&utm_source=footer>.
> For more options, visit https://groups.google.com/d/optout.

Grabli66 None

unread,
Sep 7, 2015, 9:14:17 AM9/7/15
to Crystal
Greate thanks.
Reply all
Reply to author
Forward
0 new messages