Skip to content
This repository has been archived by the owner on Mar 18, 2021. It is now read-only.

@Bind.query('--') to Enum gives "No static parse method error" while static parse method is defined in Extension on that Enum. #861

Closed
akasher opened this issue Jun 18, 2020 · 6 comments

Comments

@akasher
Copy link

akasher commented Jun 18, 2020

enum Roles {
  owner,
  admin,
  user,
}

extension rolesParser on Roles {
  static Roles parse(String value) {
    final Roles role = tryParse(value);
    if (role != null)
      return role;
  }
  static Roles tryParse(String input) {
    final String value = input.trim();
    return Roles.values.firstWhere((element) => element.toString().split('.')[1].toUpperCase() == value.toUpperCase());
  }
}

Bad state: Bad state: Invalid binding 'role' on 'UsersController.getUsers': Parameter type does not implement static parse method.
**** Stacktrace


@Reductions
Copy link
Contributor

Please when you post code use a "code block".

@Reductions
Copy link
Contributor

Reductions commented Jun 18, 2020

enum Roles {
  owner,
  admin,
  user,
}

extension RolesParser on Roles {
  // You can not add static methods extension. The code below allows you do this `RolesParser.parse()` not `Roles.parse()`  
  static Roles parse(String value) {
    final Roles role = tryParse(value);
    if (role != null) return role;
  }

  static Roles tryParse(String input) {
    final String value = input.trim();
    return Roles.values.firstWhere((element) =>
        element.toString().split('.')[1].toUpperCase() == value.toUpperCase());
  }
}

@Reductions
Copy link
Contributor

Reductions commented Jun 18, 2020

What I would do is either bind to a string and then parse it or do something like:

class RoleBind {
  RoleBind._(this.value);

  final Role value;

  static RoleBind parse(String input) {
    final result = RoleBind.tryParse(input);
    if (result != null) {
      return result;
    }
    throw 'Cound not parse Role';
  }

  static RoleBind tryParse(String input) {
    final value = input.trim();
    final eValue = Role.values.firstWhere((role) =>
      role.toString().split('.').last.toUppperCase() == value.toUpperCase());
    if(eValue != null) {
        return RoleBind._(eValue);
    }
    return null;
  }
}

@Reductions
Copy link
Contributor

I would also recommend renaming Roles to Role as it is more natural to say Role.user then Roles.user.

@akasher
Copy link
Author

akasher commented Jun 18, 2020

Please when you post code use a "code block".
I apologize, I have done the needful. Thanks.

@akasher
Copy link
Author

akasher commented Jun 18, 2020

@Reductions , your advice to make another class called RoleBind worked like a charm. Thanks a ton.

@akasher akasher closed this as completed Jun 18, 2020
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants