1 # Redmine - project management software
2 # Copyright (C) 2006-2011 Jean-Philippe Lang
3 #
4 # This program is free software; you can redistribute it and/or
5 # modify it under the terms of the GNU General Public License
6 # as published by the Free Software Foundation; either version 2
7 # of the License, or (at your option) any later version.
8 #
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
13 #
14 # You should have received a copy of the GNU General Public License
15 # along with this program; if not, write to the Free Software
16 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17
18 module Redmine
19 class CustomFieldFormat
20 include Redmine::I18n
21
22 cattr_accessor :available
23 @@available = {}
24
25 attr_accessor :name, :order, :label, :edit_as, :class_names
26
27 def initialize(name, options={})
28 self.name = name
29 self.label = options[:label]
30 self.order = options[:order]
31 self.edit_as = options[:edit_as] || name
32 self.class_names = options[:only]
33 end
34
35 def format(value)
36 send "format_as_#{name}", value
37 end
38
39 def format_as_date(value)
40 begin; format_date(value.to_date); rescue; value end
41 end
42
43 def format_as_bool(value)
44 l(value == "1" ? :general_text_Yes : :general_text_No)
45 end
46
47 ['string','text','int','float','list'].each do |name|
48 define_method("format_as_#{name}") {|value|
49 return value
50 }
51 end
52
53 ['user', 'version'].each do |name|
54 define_method("format_as_#{name}") {|value|
55 return value.blank? ? "" : name.classify.constantize.find_by_id(value.to_i).to_s
56 }
57 end
58
59 class << self
60 def map(&block)
61 yield self
62 end
63
64 # Registers a custom field format
65 def register(custom_field_format, options={})
66 @@available[custom_field_format.name] = custom_field_format unless @@available.keys.include?(custom_field_format.name)
67 end
68
69 def available_formats
70 @@available.keys
71 end
72
73 def find_by_name(name)
74 @@available[name.to_s]
75 end
76
77 def label_for(name)
78 format = @@available[name.to_s]
79 format.label if format
80 end
81
82 # Return an array of custom field formats which can be used in select_tag
83 def as_select(class_name=nil)
84 fields = @@available.values
85 fields = fields.select {|field| field.class_names.nil? || field.class_names.include?(class_name)}
86 fields.sort {|a,b|
87 a.order <=> b.order
88 }.collect {|custom_field_format|
89 [ l(custom_field_format.label), custom_field_format.name ]
90 }
91 end
92
93 def format_value(value, field_format)
94 return "" unless value && !value.empty?
95
96 if format_type = find_by_name(field_format)
97 format_type.format(value)
98 else
99 value
100 end
101 end
102 end
103 end
104 end