Skip to content

Commit

Permalink
Add #escape to allow clients to escape special characters
Browse files Browse the repository at this point in the history
  • Loading branch information
monkbroc committed Aug 29, 2015
1 parent 830f7c1 commit 2478c6e
Show file tree
Hide file tree
Showing 4 changed files with 27 additions and 0 deletions.
3 changes: 3 additions & 0 deletions changelog.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
# 1.3.0 - unreleased
- Add `#escape` to allow clients to escape special characters

# 1.2.1
- use `#scrub` to (more selectively) strip invalid characters from strings before attempting to format. This allows valid japanese (and more) characters to be used. Thanks to @fukayatsu for reporting.

Expand Down
6 changes: 6 additions & 0 deletions lib/slack-notifier.rb
Original file line number Diff line number Diff line change
Expand Up @@ -46,5 +46,11 @@ def username= username
default_payload[:username] = username
end

HTML_ESCAPE_REGEXP = /[&><]/
HTML_ESCAPE = { '&' => '&amp;', '>' => '&gt;', '<' => '&lt;' }

def escape(text)
text.gsub(HTML_ESCAPE_REGEXP, HTML_ESCAPE)
end
end
end
10 changes: 10 additions & 0 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,16 @@ notifier.ping message

You can see [Slack's message documentation here](https://api.slack.com/docs/formatting)

## Escaping

Since sequences starting with < have special meaning in Slack, you should use `notifier.escape` if your messages may contain &, < or >.

```ruby
link_text = notifier.escape("User <user@example.com>")
message = "Write to [#{link_text}](mailto:user@example.com)"
notifier.ping message
```

## Additional parameters

Any key passed to the `ping` method is posted to the webhook endpoint. Check out the [Slack webhook documentation](https://my.slack.com/services/new/incoming-webhook) for the available parameters.
Expand Down
8 changes: 8 additions & 0 deletions spec/lib/slack-notifier_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -109,4 +109,12 @@
expect( subject.username ).to eq "foo"
end
end

describe "#escape" do
it "escapes sequences of < > &, but not quotes" do
message = %q(I've heard "Do > with <" & that sounds ridiculous.)
expected = %q(I've heard "Do &gt; with &lt;" &amp; that sounds ridiculous.)
expect( subject.escape(message) ).to eq expected
end
end
end

0 comments on commit 2478c6e

Please sign in to comment.