Module: Labelizer::ClassMethods

Defined in:
lib/labelizer.rb

Instance Method Summary collapse

Instance Method Details

#labelizedObject



19
20
21
22
23
24
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/labelizer.rb', line 19

def labelized
  @labelized ||= Container.new([]){|attr_labelized,attr|
    model = self.to_s.underscore
    values = __send__(attr.to_s.pluralize)
    labelized = Container.new(values, accept_array_key: true){|value_labelized,value|
      data = labelized.instance_variable_get(:@data)
      attr_label_types = data[:label_types]
      attr_converter = data[:converter]

      unless labelized.has_key?(value)
        Container.new(attr_label_types){|h,label_type|
          h[label_type] = value.map{|val| value_labelized[val][label_type]}
        }
      else
        value_labelized[value] = Container.new(attr_label_types){|h,label_type|
          if label_type == :value
            result = value
          else
            result = ::I18n.translate(
              "labelizer.#{model}.#{attr}.#{value}.#{label_type}",
              default: [
                :"labelizer.#{model}.#{attr}.#{label_type}",
                :"labelizer.#{model}.#{label_type}",
                :"labelizer.#{label_type}",
                "",
              ],
            )
            if c = attr_converter[label_type]
              result = c[result]
            end
          end
          h[label_type] = result
        }
      end
    }

    labelized.singleton_class.class_eval do
      define_method :pluck do |*require_label_types|
        map{|value,label_type_labelized|
          require_label_types.map{|require_label_type|
            label_type_labelized[require_label_type]
          }
        }
      end
    end

    attr_labelized[attr] = labelized
  }
end