Class: PrettyValidation::Validation

Inherits:
Object
  • Object
show all
Defined in:
lib/pretty_validation/validation.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(method_name, column_name, options = nil) ⇒ Validation

Returns a new instance of Validation.



36
37
38
39
40
# File 'lib/pretty_validation/validation.rb', line 36

def initialize(method_name, column_name, options = nil)
  @method_name = method_name
  @column_name = column_name
  @options = options
end

Instance Attribute Details

#column_nameObject (readonly)

Returns the value of attribute column_name.



7
8
9
# File 'lib/pretty_validation/validation.rb', line 7

def column_name
  @column_name
end

#method_nameObject (readonly)

Returns the value of attribute method_name.



7
8
9
# File 'lib/pretty_validation/validation.rb', line 7

def method_name
  @method_name
end

#optionsObject (readonly)

Returns the value of attribute options.



7
8
9
# File 'lib/pretty_validation/validation.rb', line 7

def options
  @options
end

Class Method Details

.sexy_validations(table_name) ⇒ Object



9
10
11
12
13
14
15
16
17
18
19
20
# File 'lib/pretty_validation/validation.rb', line 9

def self.sexy_validations(table_name)
  columns = Schema.columns(table_name)
  columns = columns.reject { |x| x.name.in? %w(id created_at updated_at) }

  columns.map do |column|
    options = {}
    options[:presence] = true unless column.null
    options[:numericality] = true if column.type == :integer

    Validation.new('validates', column.name.to_sym, options) if options.present?
  end.compact
end

.unique_validations(table_name) ⇒ Object



22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/pretty_validation/validation.rb', line 22

def self.unique_validations(table_name)
  Schema.indexes(table_name).select(&:unique).reverse.map do |x|
    column_name = x.columns[0]
    scope = x.columns[1..-1].map(&:to_sym)
    options = if scope.size > 1
                { scope: scope }
              elsif scope.size == 1
                { scope: scope[0] }
              end

    Validation.new('validates_uniqueness_of', column_name.to_sym, options)
  end
end

Instance Method Details

#==(other) ⇒ Object



42
43
44
45
46
# File 'lib/pretty_validation/validation.rb', line 42

def ==(other)
  method_name == other.method_name &&
    column_name == other.column_name &&
    options == other.options
end

#to_sObject



48
49
50
51
52
53
54
# File 'lib/pretty_validation/validation.rb', line 48

def to_s
  if options.blank?
    "#{method_name} #{column_name.inspect}"
  else
    "#{method_name} #{column_name.inspect}, #{options.to_s}"
  end
end