Created
July 3, 2013 19:28
-
-
Save edipofederle/5921941 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #o model cliente tem todos os campos necessários. | |
| # porem ele não tem comportamento nenhum. | |
| class Client < ActiveRecord::Base | |
| attr_accessor :name, :cpf, :type, :cnpj | |
| end | |
| #Agora temos as especializações deles: | |
| class LegalPerson < Client | |
| validates_presence_of :cnpj | |
| def company_name | |
| "Client company name" | |
| end | |
| end | |
| class NaturalPerson < Client | |
| validates_presence_of :cpf | |
| def some_method_only_for_natural_person | |
| raise "implement it" | |
| end | |
| end | |
| #Pode-se notar que NaturalPerson e LegalPerson possuem compotamentos relacionados apenas a elas mesmas. | |
| #Nosso schema fica assim: | |
| create_table "clients", :force => true do |t| | |
| t.string "name" | |
| t.string "cpf" | |
| t.string "cnpj" | |
| t.string "type" | |
| t.datetime "created_at", :null => false | |
| t.datetime "updated_at", :null => false | |
| end | |
| #Nota-se a columa type, é por meio desta que o ActiveRecord identifica qual "Classe" foi usada para criar o Cliente. | |
| # Entao podemos fazer coisas assim: | |
| a = LegalPerson.new | |
| => #<LegalPerson id: nil, name: nil, cpf: nil, cnpj: nil, type: "LegalPerson", created_at: nil, updated_at: nil> | |
| 1.9.3-p194 :025 > a.name = "edipo" | |
| => "edipo" | |
| 1.9.3-p194 :026 > a.cnpj = "101001" | |
| => "101001" | |
| 1.9.3-p194 :027 > a.save! | |
| 1.9.3-p194 :031 > a.name | |
| => "edipo" | |
| 1.9.3-p194 :032 > a.type | |
| => "LegalPerson" | |
| #O AC automaticamente identifica qual model é e inclui ele no atributo type. | |
| #Legal não? |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment