Class: BasicField

Inherits:
Object
  • Object
show all
Includes:
Helpers
Defined in:
lib/formalize/field.rb

Instance Method Summary collapse

Methods included from Helpers

#tag, #tag_attributes, #tag_content

Constructor Details

#initialize(id, opts = {}) ⇒ BasicField

Returns a new instance of BasicField.



7
8
9
10
11
# File 'lib/formalize/field.rb', line 7

def initialize(id, opts={})
  @errors = []
  @opts = opts
  @opts[:name] = id
end

Instance Method Details

#errorsObject



18
19
20
21
22
23
24
# File 'lib/formalize/field.rb', line 18

def errors
  # REVIEW: What gets returned when @errors is empty?
  unless @errors.empty?
    list_items = @errors.collect { |error| tag_content(:li, error)}.join("\n")
    tag_content(:ul, list_items, {:class => 'errors'})
  end
end

#errors=(message) ⇒ Object



26
27
28
# File 'lib/formalize/field.rb', line 26

def errors=(message)
  @errors.push(message)
end

#input(attrs = @opts) ⇒ Object



13
14
15
16
# File 'lib/formalize/field.rb', line 13

def input(attrs = @opts)
  input = tag(:input, attrs)
  attrs[:label] ? tag_content(:label, "#{ attrs[:label] } #{ input }") : input
end

#valid?Boolean

Returns:

  • (Boolean)


38
39
40
# File 'lib/formalize/field.rb', line 38

def valid?
  @errors.empty?
end

#validateObject



42
43
44
45
46
47
48
# File 'lib/formalize/field.rb', line 42

def validate
  validate_presence if @opts.has_key?(:required)
  validate_length if @opts.has_key?(:maxlength)
  unless @opts[:value].nil? || @opts[:value].is_a?(Array) || @opts[:value].strip.empty?
    validate_format if @opts.has_key?(:pattern)
  end
end

#validate_formatObject



62
63
64
65
66
67
# File 'lib/formalize/field.rb', line 62

def validate_format
  re = Regexp.new(@opts[:pattern])
  unless  re =~ @opts[:value]
    @errors << "#{ @opts[:name].capitalize } must be in a valid format"
  end
end

#validate_lengthObject



56
57
58
59
60
# File 'lib/formalize/field.rb', line 56

def validate_length
  if @opts[:value].size > @opts[:maxlength].to_i
    @errors << "#{ @opts[:name].capitalize } must not be more than #{ @opts[:maxlength] } characters long"
  end
end

#validate_presenceObject



50
51
52
53
54
# File 'lib/formalize/field.rb', line 50

def validate_presence
  if @opts[:required] == true && @opts[:value].strip.empty?
    @errors << "#{ @opts[:name].capitalize } must not be blank"
  end
end

#valueObject



30
31
32
# File 'lib/formalize/field.rb', line 30

def value
  @opts[:value]
end

#value=(val) ⇒ Object



34
35
36
# File 'lib/formalize/field.rb', line 34

def value=(val)
  @opts[:value] = val
end