Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Extending from custom class gives @@validators errors #238

Closed
Thellior opened this issue Jun 20, 2018 · 2 comments
Closed

Extending from custom class gives @@validators errors #238

Thellior opened this issue Jun 20, 2018 · 2 comments

Comments

@Thellior
Copy link
Contributor

When creating an application_record.cr and extending it Granite::Base it works.
When i create an model user.cr and extend from application_record.cr it will raise an compiler error saying that @@Validators are already defined.

class ApplicationRecord < Granite::Base
  adapter pg
end
class User < ApplicationRecord
  # Table
  table_name users

  # Fields
  field username : String
  field password : String

  timestamps

  # Validations
  validate_not_blank :username
  validate_not_blank :password
  validate_uniqueness :username
end
Error in src/models/user.cr:1: expanding macro

class User < ApplicationRecord
^

in macro 'inherited' expanded macro: included:1, line 1:

>  1.       @@validators = Array({field: String, message: String, block: Proc(self, Bool)}).new
   2.
   3.       def self.validate(message : String, &block : self -> Bool)
   4.         self.validate(:base, message, block)
   5.       end
   6.
   7.       def self.validate(field : (Symbol | String), message : String, &block : self -> Bool)
   8.         self.validate(field, message, block)
   9.       end
  10.
  11.       def self.validate(message : String, block : self -> Bool)
  12.         self.validate(:base, message, block)
  13.       end
  14.
  15.       def self.validate(field : (Symbol | String), message : String, block : self -> Bool)
  16.         @@validators << {field: field.to_s, message: message, block: block}
  17.       end
  18.

class variable '@@validators' of User is already defined as Array(NamedTuple(field: String, message: String, block: Proc(ApplicationRecord, Bool))) in ApplicationRecord
@robacarp
Copy link
Member

Yeah, right now this isn't supported on Granite.

The easiest way to accomplish what you're trying to do is with a module which you import into your models. I do this and it works reasonably well. I'm not sure it'll work with the adapter macro though.

@Blacksmoke16
Copy link
Contributor

Duplicate of #123

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

No branches or pull requests

3 participants