Sha256: 48b9fc04c93a6fa290fcc42b813a0becbade5c8683e1c989bef5f8ba4a617bc9

Contents?: true

Size: 1.38 KB

Versions: 1

Compression:

Stored size: 1.38 KB

Contents

# frozen_string_literal: true

require 'sweet-moon'

module NanoBot
  module Components
    class Adapter
      def self.apply(_direction, params)
        content = params[:content]

        if params[:fennel] && params[:lua]
          raise StandardError, 'Adapter conflict: You can only use either Lua or Fennel, not both.'
        end

        if params[:fennel]
          content = fennel(content, params[:fennel])
        elsif params[:lua]
          content = lua(content, params[:lua])
        end

        "#{params[:prefix]}#{content}#{params[:suffix]}"
      end

      def self.fennel(content, expression)
        path = "#{File.expand_path('../static/fennel', __dir__)}/?.lua"
        state = SweetMoon::State.new(package_path: path).fennel
        # TODO: global is deprecated...
        state.fennel.eval(
          "(global adapter (fn [content] #{expression}))", 1,
          { allowedGlobals: %w[math string table] }
        )
        adapter = state.get(:adapter)
        adapter.call([content])
      end

      def self.lua(content, expression)
        state = SweetMoon::State.new
        code = "_, adapter = pcall(load('return function(content) return #{
          expression.gsub("'", "\\\\'")
        }; end', nil, 't', {math=math,string=string,table=table}))"

        state.eval(code)
        adapter = state.get(:adapter)
        adapter.call([content])
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
nano-bots-0.1.1 components/adapter.rb