Class: WeChat::Bot::Pattern
- Inherits:
-
Object
- Object
- WeChat::Bot::Pattern
- Defined in:
- lib/wechat/bot/pattern.rb
Overview
消息匹配
Instance Attribute Summary collapse
-
#pattern ⇒ Object
readonly
Returns the value of attribute pattern.
-
#prefix ⇒ Object
readonly
Returns the value of attribute prefix.
-
#suffix ⇒ Object
readonly
Returns the value of attribute suffix.
Class Method Summary collapse
- .generate(type, argument) ⇒ Object
- .obj_to_r(obj, anchor = nil) ⇒ Regexp?
- .resolve_proc(obj, msg = nil) ⇒ Object
Instance Method Summary collapse
-
#initialize(prefix, pattern, suffix) ⇒ Pattern
constructor
A new instance of Pattern.
- #to_r(msg = nil) ⇒ Object
Constructor Details
#initialize(prefix, pattern, suffix) ⇒ Pattern
Returns a new instance of Pattern.
44 45 46 |
# File 'lib/wechat/bot/pattern.rb', line 44 def initialize(prefix, pattern, suffix) @prefix, @pattern, @suffix = prefix, pattern, suffix end |
Instance Attribute Details
#pattern ⇒ Object (readonly)
Returns the value of attribute pattern.
42 43 44 |
# File 'lib/wechat/bot/pattern.rb', line 42 def pattern @pattern end |
#prefix ⇒ Object (readonly)
Returns the value of attribute prefix.
40 41 42 |
# File 'lib/wechat/bot/pattern.rb', line 40 def prefix @prefix end |
#suffix ⇒ Object (readonly)
Returns the value of attribute suffix.
41 42 43 |
# File 'lib/wechat/bot/pattern.rb', line 41 def suffix @suffix end |
Class Method Details
.generate(type, argument) ⇒ Object
31 32 33 34 35 36 37 38 |
# File 'lib/wechat/bot/pattern.rb', line 31 def self.generate(type, argument) case type when :ctcp Pattern.new(/^/, /#{Regexp.escape(argument.to_s)}(?:$| .+)/, nil) else raise ArgumentError, "Unsupported type: #{type.inspect}" end end |
.obj_to_r(obj, anchor = nil) ⇒ Regexp?
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
# File 'lib/wechat/bot/pattern.rb', line 6 def self.obj_to_r(obj, anchor = nil) case obj when Regexp, NilClass return obj else escaped = Regexp.escape(obj.to_s) case anchor when :start return Regexp.new("^" + escaped) when :end return Regexp.new(escaped + "$") when nil return Regexp.new(Regexp.escape(obj.to_s)) end end end |
.resolve_proc(obj, msg = nil) ⇒ Object
23 24 25 26 27 28 29 |
# File 'lib/wechat/bot/pattern.rb', line 23 def self.resolve_proc(obj, msg = nil) if obj.is_a?(Proc) return resolve_proc(obj.call(msg), msg) else return obj end end |
Instance Method Details
#to_r(msg = nil) ⇒ Object
48 49 50 51 52 53 54 55 56 57 58 59 60 61 |
# File 'lib/wechat/bot/pattern.rb', line 48 def to_r(msg = nil) pattern = Pattern.resolve_proc(@pattern, msg) case pattern when Regexp, NilClass prefix = Pattern.obj_to_r(Pattern.resolve_proc(@prefix, msg), :start) suffix = Pattern.obj_to_r(Pattern.resolve_proc(@suffix, msg), :end) /#{prefix}#{pattern}#{suffix}/ else prefix = Pattern.obj_to_r(Pattern.resolve_proc(@prefix, msg)) suffix = Pattern.obj_to_r(Pattern.resolve_proc(@suffix, msg)) /^#{prefix}#{Pattern.obj_to_r(pattern)}#{suffix}$/ end end |