Sha256: 2583c86a803f1bc23678e89404a31fef1d63aa10c7e32212a93bafd3f2f21589

Contents?: true

Size: 1009 Bytes

Versions: 27

Compression:

Stored size: 1009 Bytes

Contents

require 'shellwords'
require 'erubis'
require 'nrser'

class ShellEruby < Erubis::EscapedEruby
  def escaped_expr code
    "Shellwords.escape((#{code.strip}).to_s)"
  end
end

class ERBContext
  def initialize args, kwargs
    @args = args
    @kwargs = kwargs
    @arg_index = 0
  end

  def method_missing sym, *args, &block
    if args.empty? && block.nil?
      if sym.to_s[-1] == '?'
        key = sym.to_s[0...-1].to_sym
        @kwargs[key]
      else
        @kwargs.fetch(sym)
      end
    else
      super
    end
  end

  def get_binding
    binding
  end

  def arg
    @args.fetch(@arg_index).tap {@arg_index += 1}
  end
end

tpl = <<-BLOCK
  defaults write <%= domain %> <%= key %> -dict
  <% values.each do |key, value| %>
    <%= key %> <%= value %>
  <% end %>
BLOCK

ctx = ERBContext.new [],  domain: "com.nrser.blah",
                          key: "don't do it",
                          values: {x: '<ex>', y: 'why'}

s = NRSER.squish ShellEruby.new(tpl).result(ctx.get_binding)

puts s

Version data entries

27 entries across 27 versions & 1 rubygems

Version Path
cmds-0.2.11 scratch/erb.rb
cmds-0.2.10 scratch/erb.rb
cmds-0.2.9 scratch/erb.rb
cmds-0.2.8 scratch/erb.rb
cmds-0.2.7 scratch/erb.rb
cmds-0.2.6 scratch/erb.rb
cmds-0.2.5 scratch/erb.rb
cmds-0.2.4 scratch/erb.rb
cmds-0.2.3 scratch/erb.rb
cmds-0.2.2 scratch/erb.rb
cmds-0.2.1 scratch/erb.rb
cmds-0.2.0 scratch/erb.rb
cmds-0.1.5 scratch/erb.rb
cmds-0.1.4 scratch/erb.rb
cmds-0.1.3 scratch/erb.rb
cmds-0.1.2 scratch/erb.rb
cmds-0.1.1 scratch/erb.rb
cmds-0.1.0 scratch/erb.rb
cmds-0.0.9 scratch/erb.rb
cmds-0.0.8 scratch/erb.rb