Skip to content
Browse files

Encapsulated all encoding functionality in the Encoder class.

  • Loading branch information...
1 parent 3857d21 commit 08243f32cc5cef82f562d0f081f28136767e7730 @threedaymonk committed Aug 19, 2009
Showing with 37 additions and 35 deletions.
  1. +37 −35 lib/htmlentities.rb
View
72 lib/htmlentities.rb
@@ -76,43 +76,15 @@ def decode(source)
# contains valid UTF-8 before calling this method.
#
def encode(source, *instructions)
- string = source.to_s.dup
- e = Encoder.new(@flavor, instructions)
-
-
- string.gsub!(basic_entity_regexp){ e.encode_basic($&) }
- string.gsub!(extended_entity_regexp){ e.encode_extended($&) }
- string
+ encoder = Encoder.new(@flavor, instructions)
+ encoder.encode(source)
end
private
def map
@map ||= HTMLEntities::MAPPINGS[@flavor]
end
- def basic_entity_regexp
- @basic_entity_regexp ||= (
- case @flavor
- when /^html/
- /[<>"&]/
- else
- /[<>'"&]/
- end
- )
- end
-
- def extended_entity_regexp
- @extended_entity_regexp ||= (
- if encoding_aware?
- regexp = '[^\u{20}-\u{7E}]'
- else
- regexp = '[^\x20-\x7E]'
- end
- regexp += "|'" if @flavor == 'html4'
- Regexp.new(regexp)
- )
- end
-
def named_entity_regexp
@named_entity_regexp ||= (
min_length = map.keys.map{ |a| a.length }.min
@@ -122,11 +94,7 @@ def named_entity_regexp
)
end
- def encoding_aware?
- "1.9".respond_to?(:encoding)
- end
-
- class Encoder
+ class Encoder #:nodoc:
def initialize(flavor, instructions)
@flavor = flavor
instructions << :basic if (instructions.empty?)
@@ -135,7 +103,37 @@ def initialize(flavor, instructions)
build_extended_entity_encoder(instructions)
end
+ def encode(source)
+ string = source.to_s.dup
+ string.gsub!(basic_entity_regexp){ encode_basic($&) }
+ string.gsub!(extended_entity_regexp){ encode_extended($&) }
+ string
+ end
+
private
+ def basic_entity_regexp
+ @basic_entity_regexp ||= (
+ case @flavor
+ when /^html/
+ /[<>"&]/
+ else
+ /[<>'"&]/
+ end
+ )
+ end
+
+ def extended_entity_regexp
+ @extended_entity_regexp ||= (
+ if encoding_aware?
+ regexp = '[^\u{20}-\u{7E}]'
+ else
+ regexp = '[^\x20-\x7E]'
+ end
+ regexp += "|'" if @flavor == 'html4'
+ Regexp.new(regexp)
+ )
+ end
+
def validate_instructions(instructions)
unknown_instructions = instructions - INSTRUCTIONS
if unknown_instructions.any?
@@ -190,5 +188,9 @@ def reverse_map
uniqmap.invert
)
end
+
+ def encoding_aware?
+ "1.9".respond_to?(:encoding)
+ end
end
end

0 comments on commit 08243f3

Please sign in to comment.
Something went wrong with that request. Please try again.