custom_value.rb 2.32 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
# redMine - project management software
# Copyright (C) 2006  Jean-Philippe Lang
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
# 
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

class CustomValue < ActiveRecord::Base
  belongs_to :custom_field
  belongs_to :customized, :polymorphic => true

22
  def after_initialize
23
    if new_record? && custom_field && (customized_type.blank? || (customized && customized.new_record?))
24 25 26 27
      self.value ||= custom_field.default_value
    end
  end
  
28 29 30 31 32
  # Returns true if the boolean custom value is true
  def true?
    self.value == '1'
  end
  
33 34 35 36 37 38 39 40
  def editable?
    custom_field.editable?
  end
  
  def required?
    custom_field.is_required?
  end
  
41 42 43 44
  def to_s
    value.to_s
  end
  
45 46
protected
  def validate
47
    if value.blank?
48
      errors.add(:value, :blank) if custom_field.is_required? and value.blank?    
49
    else
50
      errors.add(:value, :invalid) unless custom_field.regexp.blank? or value =~ Regexp.new(custom_field.regexp)
51 52
      errors.add(:value, :too_short, :count => custom_field.min_length) if custom_field.min_length > 0 and value.length < custom_field.min_length
      errors.add(:value, :too_long, :count => custom_field.max_length) if custom_field.max_length > 0 and value.length > custom_field.max_length
53 54 55 56
    
      # Format specific validations
      case custom_field.field_format
      when 'int'
57
        errors.add(:value, :not_a_number) unless value =~ /^[+-]?\d+$/	
58
      when 'float'
59
        begin; Kernel.Float(value); rescue; errors.add(:value, :invalid) end
60
      when 'date'
61
        errors.add(:value, :not_a_date) unless value =~ /^\d{4}-\d{2}-\d{2}$/
62
      when 'list'
63
        errors.add(:value, :inclusion) unless custom_field.possible_values.include?(value)
64
      end
65
    end
Jean-Philippe Lang's avatar
Jean-Philippe Lang committed
66
  end
67
end