TDC2016SP - Rails Custom Validators - Não se esqueça deles

Preview:

Citation preview

RAILS

CUSTOM VALIDATORS@marcelinol

DEFAULTVALIDATORS

RAILS GENERATE MODEL PERSON

NAME:STRINGEMAIL:STRING

PERSONAL_SITE:STRING

# app/models/person.rb

> p = Person.create(name: 'Nome', personal_site: 'http://pudim.com.br')

(0.2ms) begin transaction => (...) (0.1ms) rollback transaction => (...)

> p.errors => #<ActiveModel::Errors:0x007fa06fd7c370 @base=#<Person id: nil, name: "Nome", email: nil, personal_site: "http://pudim.com.br", created_at: nil, updated_at: nil>, @messages={:email=>["can't be blank"]}>>

# app/models/person.rb

> p = Person.create(name: 'Nome', email: 'email@example.org', personal_site: 'xunda')

(0.2ms) begin transaction => (...) (0.1ms) rollback transaction => (...)

> p.errors => #<ActiveModel::Errors:0x007fa06ff84618 @base=#<Person id: nil, name: "Nome", email: "email@example.org", personal_site: "xunda", created_at: nil, updated_at: nil>, @messages={:personal_site=>["Formato de site inválido"]}>>

> p = Person.create(name: 'Nome', email: 'email@example.org', personal_site: 'xunda')

(0.2ms) begin transaction => (...) (0.1ms) rollback transaction => (...)

> p.errors => #<ActiveModel::Errors:0x007fa06ff84618 @base=#<Person id: nil, name: "Nome", email: "email@example.org", personal_site: "xunda", created_at: nil, updated_at: nil>, @messages={:personal_site=>["Formato de site inválido"]}>>

RAILS GENERATE MODEL COMPANY

NAME:STRINGOTHER_PARAMS:XUNDA

SITE:STRING

# app/models/company.rb

# app/models/company.rb

ISTO NÃO É

DRY

É HORA DE USAR UM

CUSTOM VALIDATOR

# app/validators/url_format_validator.rb

# app/models/person.rb

# app/models/company.rb

> p = Person.create(name: 'Nome', email: 'email@example.org', personal_site: 'xunda')

(0.2ms) begin transaction => (...) (0.1ms) rollback transaction => (...)

> p.errors => #<ActiveModel::Errors:0x007fa06ff84618 @base=#<Person id: nil, name: "Nome", email: "email@example.org", personal_site: "xunda", created_at: nil, updated_at: nil>, @messages={:personal_site=>["Formato de site inválido"]}>>

# app/models/xunda.rb

if rails.too_old

end

VAMOS TESTAR?

CARA, ISSO PODE FICAR AINDA MAIS

BONITO?

SIM

CRIE UM VALIDATION TESTER

# spec/support/validation_tester.rb

# spec/support/validation_tester.rb

SHIPIT.RESULTADOSDIGITAIS.COM.BR

PERGUNTAS?CONSIDERAÇÕES?

@marcelinol

Obrigado