Module: Formz::Models

Defined in:
lib/formz/models.rb

Overview

Formz::Models

Instance Method Summary collapse

Instance Method Details

#create_tag(name, contents, attrs, &block) ⇒ Object



51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
# File 'lib/formz/models.rb', line 51

def create_tag name, contents, attrs, &block
  unless name == :form || form_context.blank?
    model, tag_name = form_context.last, attrs[:name]
    if attrs[:value].nil?
      if attrs[:name] && model_has_property?(model, attrs[:name])
        # Errors
        if errors = model.errors.on(attrs[:name])
          attrs[:error] = errors.first
        end
        # Values
        attrs[:name] = '%s[%s]' % [model_name(model), tag_name]
        value = model.send tag_name
        case name
        when :textarea ; contents = value
        else             attrs[:value] = value
        end
      end
    end
    if default = attrs.delete(:default)
      attrs[:value] = default if attrs[:value].nil?
    end
  end
  super
end

#form_contextObject

Form context model stack.



13
14
15
# File 'lib/formz/models.rb', line 13

def form_context
  $__form_context ||= []
end

#form_for(model, attrs = {}, &block) ⇒ Object

Return a form in context to model. model may be an object, class, or symbol.



32
33
34
35
36
37
38
# File 'lib/formz/models.rb', line 32

def form_for model, attrs = {}, &block
  model = Object.const_get model.to_s.capitalize if model.is_a? Symbol
  model = model.new if model.is_a? Class
  with_form_context model do
    form model_name(model), attrs, &block  
  end
end

#model_has_property?(model, property_name) ⇒ Boolean

Check if model has property_name.

Returns:

  • (Boolean)


79
80
81
82
83
# File 'lib/formz/models.rb', line 79

def model_has_property? model, property_name
  model.send(:properties).any? do |property|
    property.name == property_name.to_sym
  end
end

#model_name(model) ⇒ Object

Return lowercase name of model. Forum::Post will become :post, etc.



89
90
91
# File 'lib/formz/models.rb', line 89

def model_name model
  model.class.to_s.split('::').last.downcase.to_sym
end

#select(name, options, attrs = {}) ⇒ Object



40
41
42
43
44
45
46
47
48
49
# File 'lib/formz/models.rb', line 40

def select name, options, attrs = {}
  if model = form_context.last
    if model_has_property? model, name
      if value = model.send(name)
        attrs[:selected] ||= value
      end
    end
  end
  super
end

#with_form_context(model, &block) ⇒ Object

Push model as the current context while executing block; returning block’s results.



21
22
23
24
25
26
# File 'lib/formz/models.rb', line 21

def with_form_context model, &block
  form_context.push model
  result = yield
  form_context.pop
  result
end