Module: JSMin

Defined in:
lib/jsmin.rb

Overview

JSMin

Ruby implementation of Douglas Crockford’s JavaScript minifier, JSMin.

Author

Ryan Grove ([email protected])

Version

1.0.0 (2008-03-22)

Copyright

Copyright © 2008 Ryan Grove. All rights reserved.

Website

github.com/rgrove/jsmin/

Example

require 'rubygems'
require 'jsmin'

File.open('example.js', 'r') {|file| puts JSMin.minify(file) }

Constant Summary collapse

ORD_LF =
"\n"[0].freeze
ORD_SPACE =
' '[0].freeze

Class Method Summary collapse

Class Method Details

.minify(input) ⇒ Object

Reads JavaScript from input (which can be a String or an IO object) and returns a String containing minified JS.



56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
# File 'lib/jsmin.rb', line 56

def minify(input)
  @js = StringScanner.new(input.is_a?(IO) ? input.read : input.to_s)

  @a         = "\n"
  @b         = nil
  @lookahead = nil
  @output    = ''
  
  action_get
  
  while !@a.nil? do
    case @a
    when ' '
      if alphanum?(@b)
        action_output
      else
        action_copy
      end
      
    when "\n"
      if @b == ' '
        action_get
      elsif @b =~ /[{\[\(+-]/
        action_output
      else
        if alphanum?(@b)
          action_output
        else
          action_copy
        end
      end
      
    else
      if @b == ' '
        if alphanum?(@a)
          action_output
        else
          action_get
        end
      elsif @b == "\n"
        if @a =~ /[}\]\)\\"+-]/
          action_output
        else
          if alphanum?(@a)
            action_output
          else
            action_get
          end
        end
      else
        action_output
      end
    end
  end
  
  @output
end