Skip to content
This repository has been archived by the owner on Jun 30, 2022. It is now read-only.

Commit

Permalink
Add Lita::Util.underscore for robust namespace generation.
Browse files Browse the repository at this point in the history
  • Loading branch information
jimmycuadra committed Jul 4, 2013
1 parent 62b3857 commit 66a6735
Show file tree
Hide file tree
Showing 5 changed files with 47 additions and 1 deletion.
1 change: 1 addition & 0 deletions lib/lita.rb
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ def run(config_path = nil)
end
end

require "lita/util"
require "lita/logger"
require "lita/user"
require "lita/source"
Expand Down
2 changes: 1 addition & 1 deletion lib/lita/handler.rb
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ def http_routes

def namespace
if name
name.split("::").last.downcase
Util.underscore(name.split("::").last)
else
raise "Handlers that are anonymous classes must define self.name."
end
Expand Down
20 changes: 20 additions & 0 deletions lib/lita/util.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
module Lita
module Util
ACRONYM_REGEX = /(?=a)b/

class << self
def underscore(camel_cased_word)
word = camel_cased_word.to_s.dup
word.gsub!('::', '/')
word.gsub!(/(?:([A-Za-z\d])|^)(#{ACRONYM_REGEX})(?=\b|[^a-z])/) do
"#{$1}#{$1 && '_'}#{$2.downcase}"
end
word.gsub!(/([A-Z\d]+)([A-Z][a-z])/,'\1_\2')
word.gsub!(/([a-z\d])([A-Z])/,'\1_\2')
word.tr!("-", "_")
word.downcase!
word
end
end
end
end
16 changes: 16 additions & 0 deletions spec/lita/handler_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -86,4 +86,20 @@ def self.name
handler_class.dispatch(robot, message)
end
end

describe ".namespace" do
it "provides a snake cased namespace for the handler" do
handler_class = Class.new(described_class) do
def self.name
"Lita::Handlers::FooBarBaz"
end
end
expect(handler_class.namespace).to eq("foo_bar_baz")
end

it "raises an exception if the handler doesn't define self.name" do
handler_class = Class.new(described_class)
expect { handler_class.namespace }.to raise_error
end
end
end
9 changes: 9 additions & 0 deletions spec/lita/util_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
require "spec_helper"

describe Lita::Util do
describe ".underscore" do
it "converts camel cased strings into snake case" do
expect(described_class.underscore("FooBarBaz")).to eq("foo_bar_baz")
end
end
end

0 comments on commit 66a6735

Please sign in to comment.