Class: RuleSet

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

Direct Known Subclasses

Parser

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Hash

#create_path, #defaults, #prep_insert, #required, #select

Constructor Details

#initialize(rules = {}) ⇒ RuleSet

Returns a new instance of RuleSet


150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
# File 'lib/magic_parser.rb', line 150

def initialize rules = {}
	if block_given?
		rules = yield
	end

	rules.assert_type Hash

	rules.each { |name, rule|
		pattern, subrule = rule
		if !subrule
			subrule = {}
	  end
		self[name] = Rule.new( name, pattern, subrule )
	}
end

Class Method Details

.parse(text: '', file: nil) ⇒ Object


192
193
194
195
196
197
198
199
200
# File 'lib/magic_parser.rb', line 192

def RuleSet.parse text: '', file: nil
	check_args [text, file], [String, [String, NilClass]]

	if file
		text = File.read( file )
	end

	apply Token.new( nil, text.force_encoding('UTF-8') )
end

Instance Method Details

#apply(token) ⇒ Object


174
175
176
177
178
179
180
181
182
183
184
185
186
# File 'lib/magic_parser.rb', line 174

def apply token
	if token.kind_of? String
		token = Token.new( token )
	end

	token.assert_type Token

	each { |name, rule|
		token = rule.apply token
	}

	token
end

#parse(text: '', file: nil) ⇒ Object


188
189
190
# File 'lib/magic_parser.rb', line 188

def parse text: '', file: nil
	Parser.parse text, file
end

#to_sObject


166
167
168
169
170
171
172
# File 'lib/magic_parser.rb', line 166

def to_s
	out = ''
	each { |name, rule|
		out += "#{rule}\n"
	}
	out
end