Class: Formize::Generator::Column

Inherits:
Object
  • Object
show all
Defined in:
lib/formize/generator.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(model, name, options = {}) ⇒ Column

@@count = 0



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/formize/generator.rb', line 9

def initialize(model, name, options={})
  @model = model
  @name = name.to_s
  @filter = options.delete(:filter) || "%X%"
  @code = options.delete(:code)
  @interpolation_key = options.delete(:interpolation_key) || @name.gsub(/\W/, '_')
  klass = @model
  @through = (options.delete(:through) || []).collect do |reflection|
    unless klass.reflections[reflection.to_sym]
      raise Exception.new("Model #{klass.name} has no reflections #{reflection.inspect}")
    end
    klass = klass.reflections[reflection.to_sym].class_name.constantize
    reflection.to_sym
  end || []
  @column = foreign_model.columns_hash[@name]
end

Instance Attribute Details

#columnObject (readonly)

Returns the value of attribute column.



5
6
7
# File 'lib/formize/generator.rb', line 5

def column
  @column
end

#filterObject (readonly)

Returns the value of attribute filter.



5
6
7
# File 'lib/formize/generator.rb', line 5

def filter
  @filter
end

#interpolation_keyObject (readonly)

Returns the value of attribute interpolation_key.



5
6
7
# File 'lib/formize/generator.rb', line 5

def interpolation_key
  @interpolation_key
end

#nameObject (readonly)

Returns the value of attribute name.



5
6
7
# File 'lib/formize/generator.rb', line 5

def name
  @name
end

Instance Method Details

#foreign_modelObject



52
53
54
55
56
57
58
# File 'lib/formize/generator.rb', line 52

def foreign_model
  model = @model
  for reflection in @through
    model = model.reflections[reflection].class_name.constantize
  end
  return model
end

#sql_nameObject



26
27
28
# File 'lib/formize/generator.rb', line 26

def sql_name
  return "#{foreign_model.table_name}.#{@name}"
end

#typeObject



48
49
50
# File 'lib/formize/generator.rb', line 48

def type
  @column.type
end

#value_code(record = 'record') ⇒ Object



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/formize/generator.rb', line 30

def value_code(record='record')
  code  = "("
  value = "(#{record}#{'.'+@through.join('.') unless @through.empty?}.#{name})"
  @through.each_index do |i|
    code << "#{record}.#{@through[0..i].join('.')}.nil? ? '' : "
  end
  code << if @code
            @code.gsub(/RECORD/, record).gsub(/DATUM/, value)
          elsif[:date, :datetime, :timestamp].include? self.type
            "(#{value}.nil? ? '' : ::I18n.localize(#{value}))"
          else
            value
          end
  code << ")"
  code << ".to_s" unless name.to_s == "count"
  return code
end