module FormHelper
def form_for(object_name, object, options={}, &block)
concat('<form ... >')
fields_for(object_name,object,options,&block)
concat('</form>')
end
def fields_for(object_name,object,options={}, &block)
yield builder.new(object_name,object,self,options,block)
end
def text_field(object_name, method, options = {})
InstanceTag.new(object_name, method, self, nil, options.delete(:object)).to_input_field_tag("text", options)
end
end
class FormBuilder
def initialize(object_name, object, template, options, proc)
@object_name, @object, @template, @options, @proc = object_name, object, template, options, proc
end
...
def text_field(method,options)
@template.text_field(@object_name,method,options.merge(:object => @object))
end
...
def fields_for(name, *args, &block)
name = "#{object_name}[#{name}]"
@template.fields_for(name, *args, &block)
end
end
def tag(name, options = nil, open = false, escape = true)
"<#{name}#{tag_options(options, escape) if options}" + (open ? ">" : " />")
end
def tag(name, options)
if object.respond_to?("errors") && object.errors.respond_to?("on")
error_wrapping(tag_without_error_wrapping(name, options), object.errors.on(@method_name))
else
super
end
end
def tag_options(options, escape = true)
unless options.blank?
attrs = []
if escape
options.each do |key, value|
next unless value
key = key.to_s
value = BOOLEAN_ATTRIBUTES.include?(key) ? key : escape_once(value)
attrs << %(#{key}="#{value}")
end
else
attrs = options.map { |key, value| %(#{key}="#{value}") }
end
" #{attrs.sort * ' '}" unless attrs.empty?
end
end
Tag helper is:
class InstanceTag
def initialize(object_name, method_name, template_object, local_binding = nil, object = nil)
@object_name, @method_name = object_name.to_s.dup, method_name.to_s.dup
@template_object, @local_binding = template_object, local_binding
@object = object
if @object_name.sub!(/\[\]$/,"")
if object ||= @template_object.instance_variable_get("@#{Regexp.last_match.pre_match}") and object.respond_to?(:id_before_type_cast)
@auto_index = object.id_before_type_cast
else
raise ArgumentError, "object[] naming but object param and @object var don't exist or don't respond to id_before_type_cast: #{object.inspect}"
end
end
end
def to_input_field_tag(field_type, options = {})
options = options.stringify_keys
options["size"] = options["maxlength"] || DEFAULT_FIELD_OPTIONS["size"] unless options.key?("size")
options = DEFAULT_FIELD_OPTIONS.merge(options)
if field_type == "hidden"
options.delete("size")
end
options["type"] = field_type
options["value"] ||= value_before_type_cast(object) unless field_type == "file"
add_default_name_and_id(options)
tag("input", options)
end
end
No comments:
Post a Comment