fnando / cpf_cnpj

🇧🇷 Validate, generate and format CPF/CNPJ numbers. Include command-line tools.
MIT License
239 stars 42 forks source link

Feature/improve interoperability with rails and active model serializer #3

Closed giovannibonetti closed 4 years ago

giovannibonetti commented 9 years ago

This improves integration with ActiveModelSerializer by allowing this to work (which is very handy for using the Value Object Pattern):

# app/models/user.rb
class User < ActiveRecord::Base
  validates :cpf, associated: true, allow_nil: true
  ...

  def cpf=(number)
    super(number)
    @cpf = number ? CPF.new(number) : nil
    @cpf
  end

  def cpf
    @cpf ||= CPF.new(read_attribute(:cpf)) if read_attribute(:cpf)
  end
end

...

u = User.first
u.valid? # true

u.cpf = "12345678901"
u.valid? # false
u.errors[:cpf] # "invalid"

Also, in Rails forms work better if the method responds well to "to_s"

# app/views/users/edit.html.slim

= simple_form_for(@user, url: confirmation_path(:user), html: {method: :post}) do |f|
  = f.error_notification
  = f.full_error :confirmation_token
  .form-inputs
    = f.input :name, required: true
    = f.input :cpf, required: true
  .form-actions
    = f.button :submit
<!-- HTML rendered in the browser -->

<input class="string optional" type="text" value="XXX.XXX.XXX-XX" name="user[cpf]" id="user_cpf">
pudiva commented 8 years ago

bump!

giovannibonetti commented 8 years ago

Hi!

taschetto commented 6 years ago

This PR should be merged. Please! :+1: