2011-09-02 14:33:03 -04:00
|
|
|
module SimpleForm
|
|
|
|
module Wrappers
|
2011-09-03 03:15:47 -04:00
|
|
|
# A wrapper is an object that holds several components and render them.
|
|
|
|
# A component may either be a symbol or any object that responds to `render`.
|
|
|
|
# This API allows inputs/components to be easily wrapped, removing the
|
|
|
|
# need to modify the code only to wrap input in an extra tag.
|
|
|
|
#
|
|
|
|
# `Many` represents a wrapper around several components at the same time.
|
|
|
|
# It may optionally receive a namespace, allowing it to be configured
|
|
|
|
# on demand on input generation.
|
2011-09-02 14:33:03 -04:00
|
|
|
class Many
|
|
|
|
attr_reader :namespace, :defaults, :components
|
2011-09-03 03:04:16 -04:00
|
|
|
alias :to_sym :namespace
|
2011-09-02 14:33:03 -04:00
|
|
|
|
2011-09-03 03:08:36 -04:00
|
|
|
def initialize(namespace, components, defaults={})
|
2011-09-02 14:33:03 -04:00
|
|
|
@namespace = namespace
|
2011-09-03 03:08:36 -04:00
|
|
|
@components = components
|
|
|
|
@defaults = defaults
|
2011-09-02 16:14:23 -04:00
|
|
|
@defaults[:class] = Array.wrap(@defaults[:class])
|
2011-09-02 14:33:03 -04:00
|
|
|
end
|
|
|
|
|
2011-09-03 03:01:47 -04:00
|
|
|
def render(input)
|
2011-09-02 14:33:03 -04:00
|
|
|
content = "".html_safe
|
|
|
|
options = input.options
|
|
|
|
|
|
|
|
components.each do |component|
|
|
|
|
next if options[component] == false
|
2011-09-03 03:04:16 -04:00
|
|
|
rendered = component.respond_to?(:render) ? component.render(input) : input.send(component)
|
2011-09-02 14:33:03 -04:00
|
|
|
content.safe_concat rendered.to_s if rendered
|
|
|
|
end
|
|
|
|
|
|
|
|
wrap(input, options, content)
|
|
|
|
end
|
|
|
|
|
2011-09-03 06:24:47 -04:00
|
|
|
def find(name)
|
|
|
|
return self if namespace == name
|
|
|
|
|
|
|
|
@components.each do |c|
|
|
|
|
if c.is_a?(Symbol)
|
|
|
|
return nil if c == namespace
|
|
|
|
elsif value = c.find(name)
|
|
|
|
return value
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
nil
|
2011-09-02 16:14:23 -04:00
|
|
|
end
|
|
|
|
|
2011-09-02 14:33:03 -04:00
|
|
|
private
|
|
|
|
|
|
|
|
def wrap(input, options, content)
|
2011-09-03 03:15:47 -04:00
|
|
|
return content if options[namespace] == false
|
|
|
|
|
2011-09-03 03:08:36 -04:00
|
|
|
tag = (namespace && options[:"#{namespace}_tag"]) || @defaults[:tag]
|
2011-09-02 14:33:03 -04:00
|
|
|
return content unless tag
|
|
|
|
|
2011-09-02 16:14:23 -04:00
|
|
|
klass = html_classes(input, options)
|
2011-09-02 14:33:03 -04:00
|
|
|
opts = options[:"#{namespace}_html"] || {}
|
2011-09-02 16:14:23 -04:00
|
|
|
opts[:class] = (klass << opts[:class]).join(' ').strip unless klass.empty?
|
2011-09-02 14:33:03 -04:00
|
|
|
input.template.content_tag(tag, content, opts)
|
|
|
|
end
|
2011-09-02 16:14:23 -04:00
|
|
|
|
|
|
|
def html_classes(input, options)
|
|
|
|
@defaults[:class].dup
|
|
|
|
end
|
2011-09-02 14:33:03 -04:00
|
|
|
end
|
|
|
|
end
|
2011-09-11 17:46:47 -04:00
|
|
|
end
|