Class: Rule

Inherits:
Object show all
Defined in:
lib/magic_parser.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(n, pa = /.*/, s = {}) ⇒ Rule

Returns a new instance of Rule


75
76
77
78
79
80
81
82
83
84
85
86
87
# File 'lib/magic_parser.rb', line 75

def initialize n, pa = /.*/, s = {}
	check_args [n, pa], [String, Regexp]

	@pattern = pa
	@name = n

	if block_given?
		s = yield
	end
	s.assert_type Hash

	@subrule = RuleSet.new( s )
end

Instance Attribute Details

#nameObject (readonly)

Returns the value of attribute name


73
74
75
# File 'lib/magic_parser.rb', line 73

def name
  @name
end

#patternObject (readonly)

Returns the value of attribute pattern


73
74
75
# File 'lib/magic_parser.rb', line 73

def pattern
  @pattern
end

#subruleObject (readonly)

Returns the value of attribute subrule


73
74
75
# File 'lib/magic_parser.rb', line 73

def subrule
  @subrule
end

Instance Method Details

#apply(token) ⇒ Object


97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
# File 'lib/magic_parser.rb', line 97

def apply token
	token.assert_type Token

	result = token.dup.clear

	if token.length == 0
		token << Token.new( nil, token.text )
	end

	token.each { |subtoken|
		if subtoken.name
			result << subtoken
		else
			cursor = 0
			subtoken.text.encode!('UTF-8', 'binary', invalid: :replace, undef: :replace, replace: '')
			r = subtoken.text.scan pattern

			r.each { |match|
				if match.kind_of? Array
					match = match[0]
				end

				offset = subtoken.text.index match, cursor
				if offset != cursor
					text = subtoken.text.slice(cursor .. offset-1)
					result << Token.new( nil, text )
					cursor = offset
				end

				offset = cursor + match.length
				text = subtoken.text.slice(cursor .. offset-1)
				new_subtoken = Token.new( name, text )

				if subrule
					new_subtoken = subrule.apply( new_subtoken )
				end

				result << new_subtoken
				cursor = offset
			}

			if cursor < subtoken.text.length
				text = subtoken.text.slice(cursor .. -1)
				result << Token.new( nil, text )
			end
		end
	}

	result
end

#to_sObject


89
90
91
92
93
94
95
# File 'lib/magic_parser.rb', line 89

def to_s
	out = "Rule: #{name}, pattern: #{pattern}, subrules: #{subrule.length}\n"
	subrule.each { |name, s|
		out += s.to_s
	}
	out
end