Sha256: 1120f2a56e3d4b3677c108fa68f3b27530c082688a4bb269f241d409d85b8fc9

Contents?: true

Size: 1.03 KB

Versions: 1

Compression:

Stored size: 1.03 KB

Contents

module DeepPluck
  class Config
    def initialize()
      @attrs = []
      @children_map = {}
    end

    def self.attribute_names_to_args(attribute_names)
      attribute_names = [attribute_names] if not attribute_names.is_a?(Array)

      config = self.new
      attribute_names.each do |attribute_name|
        attr_array = attribute_name.to_s.split('.')
        config.add(attr_array)
      end
      config.to_args
    end


    def add(attr_array)
      attr_array = [attr_array] if not attr_array.is_a?(Array)
      if attr_array.size > 1
        child_key = attr_array.slice!(0).to_sym

        @children_map[child_key] ||= self.class.new
        @children_map[child_key].add(attr_array)
      else
        @attrs << attr_array.first
      end
    end

    def to_args
      if @children_map.size > 0
        children_args = @children_map.reduce({}) do |h, (child_key, child_config)|
          h[child_key] = child_config.to_args
          h
        end
        @attrs.append(children_args)
      else
        @attrs
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
ta_deep_pluck-1.3.0 lib/deep_pluck/config.rb