ECR Templating: Throwing an error on empty vars

19 views
Skip to first unread message

Alexander Reelsen

unread,
Oct 18, 2018, 5:52:26 AM10/18/18
to crysta...@googlegroups.com
Hey,

if I have the following greeting.ecr file

Greeting, <%= @name %>!

And I am running this class against it

require "ecr"

class Greeting
  def initialize(@name : String | Nil)
  end

  ECR.def_to_s "greeting.ecr"
end

puts Greeting.new(nil).to_s

The output is Greeting, !

Is there any chance to drop this leniency by configuration and throw an exception mentioning an unset variable?

Thanks for any help!


--Alex

Ary Borenszweig

unread,
Oct 18, 2018, 7:40:18 AM10/18/18
to Crystal
Hi!

In your code you are explicitly saying that `@name` allows for String or Nil, so having nil is not an error. There's no way to make it a runtime error: accessing an instance variable will always succeed.

You have a few alternatives:
- just have `@name : String` as the type, that way you get a compile error when passing `nil`
- access name through a method that raises if `@name` is `nil`. You can use `property! name : String` for this.
Reply all
Reply to author
Forward
0 new messages