Sha256: a896b9273939cf52c15c6c547bf5ee2dbf490a45ae8ed101a512cd465758494b

Contents?: true

Size: 1.42 KB

Versions: 14

Compression:

Stored size: 1.42 KB

Contents

module Lucid
  module InterfaceRb
    # A Ruby Transform holds a Regexp and a Proc, and is created
    # by calling <tt>Transform in the <tt>support</tt> ruby files.
    # See also RbLucid.
    #
    # Example:
    #
    #   Transform /^(\d+) lucid tests$/ do |lucid_string|
    #     lucid_string.to_i
    #   end
    #
    class RbTransform
      class MissingProc < StandardError
        def message
          "Transforms must always have a proc with at least one argument"
        end
      end

      def initialize(rb_language, pattern, proc)
        raise MissingProc if proc.nil? || proc.arity < 1
        @rb_language, @regexp, @proc = rb_language, Regexp.new(pattern), proc
      end

      def match(arg)
        arg ? arg.match(@regexp) : nil
      end

      def invoke(arg)
        if matched = match(arg)
          args = matched.captures.empty? ? [arg] : matched.captures
          @rb_language.current_domain.lucid_instance_exec(true, @regexp.inspect, *args, &@proc)
        end
      end

      def to_s
         convert_captures(strip_anchors(@regexp.source))
      end

    private
      def convert_captures(regexp_source)
        regexp_source.gsub(/(\()(?!\?:)/,'(?:')
      end

      def strip_captures(regexp_source)
        regexp_source.
          gsub(/(\()/, '').
          gsub(/(\))/, '')
      end

      def strip_anchors(regexp_source)
        regexp_source.
          gsub(/(^\^|\$$)/, '')
      end
    end
  end
end

Version data entries

14 entries across 14 versions & 1 rubygems

Version Path
lucid-0.5.1 lib/lucid/interface_rb/rb_transform.rb
lucid-0.4.1 lib/lucid/interface_rb/rb_transform.rb
lucid-0.4.0 lib/lucid/interface_rb/rb_transform.rb
lucid-0.3.3 lib/lucid/interface_rb/rb_transform.rb
lucid-0.3.0 lib/lucid/interface_rb/rb_transform.rb
lucid-0.2.1 lib/lucid/interface_rb/rb_transform.rb
lucid-0.2.0 lib/lucid/interface_rb/rb_transform.rb
lucid-0.1.1 lib/lucid/interface_rb/rb_transform.rb
lucid-0.1.0 lib/lucid/interface_rb/rb_transform.rb
lucid-0.0.9 lib/lucid/interface_rb/rb_transform.rb
lucid-0.0.8 lib/lucid/interface_rb/rb_transform.rb
lucid-0.0.7 lib/lucid/interface_rb/rb_transform.rb
lucid-0.0.6 lib/lucid/interface_rb/rb_transform.rb
lucid-0.0.5 lib/lucid/interface_rb/rb_transform.rb