interface
Implementable interfaces in ruby
Installation
gem install shuber-interface
require 'interface'
Usage
Simply create a module with any methods that you’d like its implementing objects to define
module RemoteControl
# turns the device on
def on
end
# turns the device off
def off
end
end
Then use the implements
method in your classes (also aliased as implement
to conform with include
and extend
naming conventions)
class BrokenDevice
implements RemoteControl
end
BrokenDevice.new.on # NotImplementedError: BrokenDevice needs to implement 'on' for interface RemoteControl
class WorkingDevice < BrokenDevice
def on
@power = true
end
def method_missing(method, *args)
method == :off ? @power = false : super
end
def respond_to_missing?(method, include_private)
method == :off
end
end
WorkingDevice.new.on # true
WorkingDevice.new.off # false
WorkingDevice.interfaces # [RemoteControl]
Testing interface implementations
Include Interface::TestHelper
in your test framework
Test::Unit::TestCase.send(:include, Interface::TestHelper)
Then you can use assert_implements_interfaces
(aliased as assert_implements_interface
) in your tests
class BrokenDeviceTest < Test::Unit::TestCase
def test_should_implement_interfaces
assert_implements_interfaces BrokenDevice.new # Failure: unimplemented interface methods for BrokenDevice: {Remote=>["off", "on"]}
end
end
You can also explicitly list interfaces
to test
module MockInterface end
class BrokenDevice
implements Remote, MockInterface
end
class BrokenDeviceTest < Test::Unit::TestCase
def test_should_implement_mock_interface
assert_implements_interface BrokenDevice.new, MockInterface # passes
end
end
Note on Patches/Pull Requests
-
Fork the project.
-
Make your feature addition or bug fix.
-
Add tests for it. This is important so I don’t break it in a future version unintentionally.
-
Commit, do not mess with Rakefile, version, or history. (if you want to have your own version, that is fine but bump version in a commit by itself I can ignore when I pull)
-
Send me a pull request. Bonus points for topic branches.