.as() unexpected token

Hi,

I’m working on a small authorization shard for kemal applications and I’m trying to make it possible for the users to define their own UserStorableUser class. However, I get this Error: unexpected type error when I try to cast the user object .as().

I have no idea why this happens and I’m hoping that one of you can explain it to me? :)

handlers.cr

# code ...

user = context.session.object?(Kemal::Authorizer.config.user_obj_name)

if user.nil?
  # code ...
else
  user_type = Kemal::Authorizer.config.user_type
  return call_next(context) if user.as(user_type).is_admin
  #                                    ^
  # Error: unexpected token: user_type
end

# code ...

config.cr

module Kemal::Authorizer
  class Config
    INSTANCE = self.new

    # code ...

    # StorableUser is a super class that all UserStorableUser class must inherit from
    # if the user want to use their own custom type
    getter user_type : Kemal::Authorizer::StorableUser.class

    def initialize
      @user_type = Kemal::Authorizer::UserStorableObject # built-in StorableUser class
    end

    # code ...
  end

  def self.config
    Config::INSTANCE
  end
end

It’s explained here: Object - Crystal 1.0.0

The type of this expression is restricted to type by the compiler. type must be a constant or typeof() expression. It cannot be evaluated at runtime.

It’s also explained in the Language Reference. Basically, #as is primarily intended to narrow down a type from a variable that has a Union type.

Just to be sure that I understand this: I have to use typeof() inside .as()?

It depends on what you want to accomplish.

There’s also this: Class - Crystal 1.0.0

1 Like

What I want is to turn user into an object of the type is specified in Kemal::Authorizer.config.user_type :)

But I’ll have a look at those links provided, thank you :)

.cast did the trick, thank you! :D

2 Likes

Yay! :tada: