Permalink
Browse files

Use field & instance attributes in bootstrap template

  • Loading branch information...
1 parent efcb8e5 commit 18782816b3e1347215ef2aeecf6d689ec7db8345 @jamesdabbs committed Mar 13, 2013
Showing with 27 additions and 18 deletions.
  1. +4 −0 lib/cave/form.rb
  2. +11 −12 lib/cave/form/builder.rb
  3. +2 −4 lib/cave/form/field.rb
  4. +10 −2 lib/cave/model_form.rb
View
4 lib/cave/form.rb
@@ -58,6 +58,10 @@ def bind attrs={}
@bound = true
end
+ def lookup attr_name
+ send attr_name
+ end
+
def bound?
@bound
end
View
23 lib/cave/form/builder.rb
@@ -1,20 +1,19 @@
require 'action_view'
class Cave::Form::Builder < ActionView::Helpers::FormBuilder
- def bootstrap control_type, name
- error = object.errors[name]
- if object.bound?
- value = object.send name
- unless error.empty?
- error_class = 'error'
- error_html = "<span class='help-inline'>#{error.first}</span>"
- end
+ def bootstrap control_type, field
+ error = object.errors[field.name]
+ value = object.lookup field.name
+
+ if error.empty?
+ error_class = error_html = ''
else
- value = error_class = error_html = ''
+ error_class = 'error'
+ error_html = "<span class='help-inline'>#{error.first}</span>"
end
- label_html = label name, class: 'control-label'
- field_html = send control_type, name, value: value
+ label_html = label field.label, class: 'control-label'
+ field_html = send control_type, field.name, value: value
raw = %{
#{label_html}
@@ -24,6 +23,6 @@ def bootstrap control_type, name
</div>
}.squish.html_safe
- @template.content_tag 'div', raw, class: "control-group #{name} #{error_class}"
+ @template.content_tag 'div', raw, class: "control-group #{field.name} #{error_class}"
end
end
View
6 lib/cave/form/field.rb
@@ -1,10 +1,8 @@
class Cave::Form::Field
- attr_accessor :type
+ attr_accessor :name, :type, :label, :help
def initialize name, type, label=nil, help=nil
- @name = name
- @type = type
- @help = help
+ @name, @type, @label, @help = name, type, label, help
@label ||= name.to_s.gsub('_', ' ').capitalize
end
end
View
12 lib/cave/model_form.rb
@@ -10,6 +10,10 @@ def initialize instance=nil, attrs={}
self.for instance
end
+ def lookup attr_name
+ super || @instance.send(attr_name)
+ end
+
def for instance
@instance = instance
check_instance_model
@@ -26,9 +30,13 @@ def persist!
private #-----------
def check_instance_model
- model = self.class.model
if @instance
- raise TypeError.new("Instance #{@instance} is not a #{model}") unless @instance.is_a? model
+ model = self.class.model
+ # Pry alters models in such a way that the first check may fail when it
+ # shouldn't. The second should still be fairly safe.
+ unless @instance.is_a?(model) || @instance.class.name == model.name
+ raise TypeError.new "Instance #{@instance} is not a #{model}"
+ end
else
raise TypeError.new("Please specify a model class to create") unless model.is_a? Class
end

0 comments on commit 1878281

Please sign in to comment.