Module: PisPasep::ActiveRecord

Defined in:
lib/pis_pasep/pis_pasep_active_record.rb

Instance Method Summary collapse

Instance Method Details

#add_composed_class(name, klass) ⇒ Object



14
15
16
17
18
19
20
21
22
23
# File 'lib/pis_pasep/pis_pasep_active_record.rb', line 14

def add_composed_class(name, klass)
  options = {:class_name => klass, :mapping => [name.to_s, 'number'], :allow_nil => true }
  constructor = Proc.new {|number| eval(klass).new(number) }
  converter = Proc.new {|value| eval(klass).new(value) }
  begin
    composed_of name, options.merge({:constructor => constructor, :converter => converter })
  rescue Exception
    composed_of name, options { eval(klass).new(name[:number]) }
  end
end

#create_code(attribute, klass) ⇒ Object



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/pis_pasep/pis_pasep_active_record.rb', line 25

def create_code(attribute, klass)
  """
    validate :#{attribute}_valid?

    def #{attribute}_valid?
      value = read_attribute('#{attribute}')
      if !value.nil? && value.strip != '' && !#{attribute}.nil? && !#{attribute}.valid?
        self.errors.add('#{attribute}', 'número inválido')
      end
    end

    def #{attribute}=(value)
      if value.blank?
        write_attribute('#{attribute}', nil)
      elsif value.kind_of?(#{eval(klass)})
        write_attribute('#{attribute}', value.number)
      else
        begin
          c = #{eval(klass)}.new(value)
          c.valid? ? write_attribute('#{attribute}', c.number) : write_attribute('#{attribute}', value)
        rescue
          @#{attribute} = value
        end
      end
    end
  """
end

#use_as_pis_pasep(*args) ⇒ Object



7
8
9
10
11
12
# File 'lib/pis_pasep/pis_pasep_active_record.rb', line 7

def use_as_pis_pasep(*args)
  args.each do |attribute|
    add_composed_class(attribute, 'PisPasep::Base')
    module_eval create_code(attribute, 'PisPasep::Base')
  end
end