Sha256: b4ab3c9cd8fa9c84e0dceddcf2ca7982a5f70260833e3b510930dd2d859c0c24

Contents?: true

Size: 1.27 KB

Versions: 5

Compression:

Stored size: 1.27 KB

Contents

module Lurker
  class FormBuilder < RenderingController
    def initialize(params)
      @_buffer = ''
      add_to_buffer(params)
    end

    def html
      @_buffer
    end

    private

    def add_to_buffer(params, parent_accessors = [])
      params.each do |name, value|

        accessors = parent_accessors.clone << name
        if value.is_a?(Hash)
          add_to_buffer(value, accessors)
        elsif value.is_a?(Array)
          value.each_with_index do |v, i|
            if v.is_a?(Hash)
              add_to_buffer(v, accessors << i)
            else
              add_element_to_buffer(accessors, v)
            end
          end
        else
          add_element_to_buffer(accessors, value)
        end
      end
    end

    def add_element_to_buffer(accessors, value)
      @_buffer += render(
        :partial => 'param_form_element',
        :locals => {
          :accessor => "#{accessors.compact.join('.')}",
          :label => "#{print_labels(accessors)}",
          :label_text => "#{print_labels(accessors)}",
          :value => value
        }
      )
    end

    def print_labels(accessors)
      accessors.inject do |acc, label|
        if label.is_a? Numeric
          "#{acc}[]"
        else
          "#{acc}[#{label}]"
        end
      end
    end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
lurker-1.0.0 lib/lurker/form_builder.rb
lurker-0.6.12 lib/lurker/form_builder.rb
lurker-0.6.11 lib/lurker/form_builder.rb
lurker-0.6.10 lib/lurker/form_builder.rb
lurker-0.6.9 lib/lurker/form_builder.rb