Skip to content

Instantly share code, notes, and snippets.

@korkey128k
Created December 2, 2016 22:14
Show Gist options
  • Select an option

  • Save korkey128k/09d8f47e12cb2962d0663b09afa79140 to your computer and use it in GitHub Desktop.

Select an option

Save korkey128k/09d8f47e12cb2962d0663b09afa79140 to your computer and use it in GitHub Desktop.

Revisions

  1. korkey128k created this gist Dec 2, 2016.
    56 changes: 56 additions & 0 deletions awesome_nested_set_input.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,56 @@
    class AwesomeNestedSetInput < Formtastic::Inputs::CheckBoxesInput
    def to_html
    unless options[:nested_set]
    super
    else
    nested_wrapping(options)
    end
    end

    def nested_wrapping(options)
    input_wrapping do
    choices_wrapping do
    legend_html <<
    hidden_field_for_all <<
    choices_group_wrapping do
    html_template_for_nested_set(options)
    end
    end
    end
    end

    def html_template_for_nested_set(options)
    if options[:show_current_first]
    model = reflection.options[:through].to_s.singularize.camelize.constantize
    additional_collection = options[:collection].first.class.where(
    :id => model.where(object.class.name.downcase.to_sym => object).pluck(:category_id)
    ).where(:parent_id => nil) rescue nil

    collection = additional_collection + options[:collection].where.not(:id => additional_collection.ids) rescue nil
    else
    collection = options[:collection]
    end

    if collection.present?
    collection.map{|menu|
    html_for_nested(menu)
    }.join("\n").html_safe
    end
    end

    def html_for_nested(menu, from_nested=false)
    choice = [menu.title, menu.id]
    first_wrap = choice_wrapping(choice_wrapping_html_options(choice)) do
    choice_html(choice) << sub_children(menu)
    end
    end

    def sub_children(menu)
    template.content_tag( :ul,
    menu.children.collect do |child|
    html_for_nested(child, true)
    end.join("\n").html_safe,
    {:class=>"sub_item-#{menu.id} sub-item"}
    ) unless menu.leaf?
    end
    end