Module: SequenceGenerator::ActsAsSequenced::InstanceMethods

Defined in:
app/models/concerns/act_as_sequenced.rb

Instance Method Summary collapse

Instance Method Details

#set_sequential_idsObject



45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
# File 'app/models/concerns/act_as_sequenced.rb', line 45

def set_sequential_ids
  self.class.base_class.sequenced_options.each do |options|
    sequence = Sequence.where(purpose: options[:purpose], scope: send(options[:scope]))
                     .where('valid_from <= ? AND valid_till >= ?', Time.now, Time.now).first
    unless self.as_json[options[:column]].present?
      if sequence
        assign_attributes(options[:column]=> sequence.generate_sequence_number)
      else
        original_sequence = Sequence.where(purpose: options[:purpose], scope: send(options[:scope])).last
        if original_sequence.nil?
          errors.add(:sequential_id, 'Sequence is not created')
        else
          valid_from = original_sequence.valid_from
          valid_till = original_sequence.valid_till
          new_start_at = original_sequence.sequential_id
          difference = (valid_till - valid_from).to_i
          new_valid_from = Date.today
          new_valid_till = new_valid_from + difference
          if original_sequence.reset_from_next_year
            sequence = Sequence.create!(original_sequence.as_json.except('id', 'start_at',
                                                                         'valid_from', 'valid_till',
                                                                         'sequential_id',
                                                                         'created_at', 'updated_at')
                                            .merge!(start_at: 1,
                                                    valid_from: new_valid_from,
                                                    valid_till: new_valid_till,
                                                    sequential_id: 1))
          else
            sequence = Sequence.create!(original_sequence.as_json.except('id', 'start_at',
                                                                         'valid_from', 'valid_till',
                                                                         'sequential_id',
                                                                         'created_at', 'updated_at')
                                            .merge!(start_at: new_start_at,
                                                    valid_from: new_valid_from,
                                                    valid_till: new_valid_till,
                                                    sequential_id: new_start_at))
          end
          assign_attributes(options[:column]=> sequence.generate_sequence_number)
        end
      end
    end
  end
end