Sha256: ed288b728c33029c8f39aadac72c71a58d0531af2d018298e78fa1069c7ca5f9

Contents?: true

Size: 1.87 KB

Versions: 5

Compression:

Stored size: 1.87 KB

Contents

module BrocadeVRouter
  class PathBuilder
    SEPARATOR = '/'.freeze
    SNAKE_TRANSFORM = ['_', '-'].map(&:freeze).freeze

    attr_reader :base_path

    def initialize(context = nil, base_path = nil, &blk)
      @base_path, @paths, @context = base_path, [], context

      if block_given?
        @context ||= eval 'self', blk.binding
        instance_eval(&blk)
      end
    end

    def to_a
      return @paths.flatten if !base_path || base_path.empty?
      @paths.flatten.map { |p| "#{base_path}/#{p}" }
    end

    private

    def route(value, &blk)
      address = URI.escape value.to_s, SEPARATOR
      @paths << address
      @paths << generate_paths!(:route, address, nil, &blk)
      @paths.last
    end

    def address(value, &blk)
      addresses = Array(value).map { |v| URI.escape v.to_s, SEPARATOR }
      @paths << generate_paths!(:address, addresses, nil, &blk)
      @paths.last
    end

    def method_missing(*args, &blk)
      return @context.send(*args) if @context.respond_to?(args.first, true)
      @paths << generate_paths!(*args, &blk)
      @paths.last
    end

    def generate_paths!(name, value = nil, exec = nil, &blk)
      path = URI.escape name.to_s.gsub(*SNAKE_TRANSFORM)

      value_is_path = @paths.pop if @paths.last == value
      @paths << "#{path}/#{value_is_path ? value : to_path(value)}" if exec

      if value.is_a?(Array)
        value.map { |v| "#{path}/#{v}" }
      else
        path = "#{path}/#{value_is_path ? value : to_path(value)}" if value
        block_given? ? PathBuilder.new(@context, path, &blk).to_a : path
      end
    end

    def to_path(value)
      val = value.is_a?(Hash) ? hash_to_ary(value) : value
      Array(val).flatten.map { |e| URI.escape e.to_s }.join SEPARATOR
    end

    def hash_to_ary(hash)
      hash.reduce([]) do |m, (k, v)|
        m << k.to_s.gsub(*SNAKE_TRANSFORM)
        m << v
      end
    end

  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
brocade_vrouter-0.3.1 lib/brocade_vrouter/path_builder.rb
brocade_vrouter-0.3.0 lib/brocade_vrouter/path_builder.rb
brocade_vrouter-0.2.4 lib/brocade_vrouter/path_builder.rb
brocade_vrouter-0.2.3 lib/brocade_vrouter/path_builder.rb
brocade_vrouter-0.2.2 lib/brocade_vrouter/path_builder.rb