Sha256: b180275e218852d940a193d0cc18c2ee82c55b601bf6e2efac8501d68ee5d330

Contents?: true

Size: 1.98 KB

Versions: 7

Compression:

Stored size: 1.98 KB

Contents

require 'callable_tree'
require 'json'
require 'rexml/document'

module Node
  module JSON
    class Parser
      include CallableTree::Node::Internal

      def match?(input, **options)
        File.extname(input) == '.json'
      end

      def call(input, **options)
        File.open(input) do |file|
          json = ::JSON.load(file)
          super(json, **options)
        end
      end

      def terminate?(_output, **)
        true
      end
    end

    class Scraper
      include CallableTree::Node::External

      def initialize(type:)
        @type = type
      end

      def match?(input, **options)
        !!input[@type.to_s]
      end

      def call(input, **options)
        input[@type.to_s]
          .map { |element| [element['name'], element['emoji']] }
          .to_h
      end
    end
  end

  module XML
    class Parser
      include CallableTree::Node::Internal

      def match?(input, **options)
        File.extname(input) == '.xml'
      end

      def call(input, **options)
        File.open(input) do |file|
          super(REXML::Document.new(file), **options)
        end
      end

      def terminate?(_output, **)
        true
      end
    end

    class Scraper
      include CallableTree::Node::External

      def initialize(type:)
        @type = type
      end

      def match?(input, **options)
        !input.get_elements("//#{@type}").empty?
      end

      def call(input, **options)
        input
          .get_elements("//#{@type}")
          .first
          .map { |element| [element['name'], element['emoji']] }
          .to_h
      end
    end
  end
end

tree = CallableTree::Node::Root.new.append(
  Node::JSON::Parser.new.append(
    Node::JSON::Scraper.new(type: :animals),
    Node::JSON::Scraper.new(type: :fruits)
  ),
  Node::XML::Parser.new.append(
    Node::XML::Scraper.new(type: :animals),
    Node::XML::Scraper.new(type: :fruits)
  )
)

Dir.glob(__dir__ + '/docs/*') do |file|
  options = { foo: :bar }
  pp tree.call(file, **options)
  puts '---'
end

Version data entries

7 entries across 7 versions & 1 rubygems

Version Path
callable_tree-0.2.3 examples/internal-seek.rb
callable_tree-0.2.2 examples/internal-seek.rb
callable_tree-0.2.1 examples/internal-seek.rb
callable_tree-0.2.0 examples/internal-seek.rb
callable_tree-0.1.3 examples/internal-seek.rb
callable_tree-0.1.2 examples/example1.rb
callable_tree-0.1.1 examples/example1.rb