Skip to content

Instantly share code, notes, and snippets.

@jc00ke
Created November 3, 2016 21:59
Show Gist options
  • Save jc00ke/3d0590a9227e960a06f34b5abed5b759 to your computer and use it in GitHub Desktop.
Save jc00ke/3d0590a9227e960a06f34b5abed5b759 to your computer and use it in GitHub Desktop.
require "json"
require "kemal"
macro build_routes(hash)
{% for route, info in hash %}
{{info[:method].id}} {{route}} do |env|
# originally I had info[:method] but that would kick out "put"
# but changing to info[:method].id kicked out put, which worked.
env.response.status_code = {{info[:status_code]}}
env.response.content_type = "application/json"
{{info[:body]}}.to_json
end
{% end %}
end
build_routes({
"/widgets/:widget_id" => {
:method => "put",
:status_code => 200,
:body => {foo: 1},
}
})
Kemal.run
@jc00ke
Copy link
Author

jc00ke commented Nov 3, 2016

I tried doing

routes = {
  "/widgets/:widget_id" => {
      :method => "put",
      :status_code => 200,
      :body => {foo: 1},
  }
}

build_routes(routes)

but I would get an error:

build_routes(routes)
^~~~~~~~~~~~

in ./src/mock_api.cr:8: for expression must be an array, hash or tuple literal, not Var:

routes

  {% for route, info in hash %}

I don't know enough about how the type system works in Crystal. Thoughts?

@mperham
Copy link

mperham commented Nov 3, 2016

You're creating routes as a local variable at runtime. Needs to be a literal to be evaluated at compile-time.

@jc00ke
Copy link
Author

jc00ke commented Nov 7, 2016

Ah, that makes sense. I ended up getting rid of that var anyway.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment