summaryrefslogtreecommitdiff
path: root/components/adapter.rb
blob: b906a27e2e764ea69e8a5c076876cb1d604aac1b (about) (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# 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
        state.fennel.eval("(set _G.adapter (fn [content] #{expression}))")
        adapter = state.get(:adapter)
        adapter.call([content])
      end

      def self.lua(content, expression)
        state = SweetMoon::State.new
        state.eval("adapter = function(content) return #{expression}; end")
        adapter = state.get(:adapter)
        adapter.call([content])
      end
    end
  end
end