Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Configure Ruby modules
require 'minitest/autorun'
module MyModule
class Configuration
attr_accessor :name, :per_page
def initialize
@per_page = 10
end
def [](value)
self.public_send(value)
end
end
def self.configure
@config ||= Configuration.new
yield(@config) if block_given?
@config
end
def self.config
@config || configure
end
end
class ConfigurationTest < MiniTest::Test
module ::MyModule
def self.reset
@config = nil
end
end
def setup
MyModule.reset
end
def test_configure_block
MyModule.configure do |config|
config.name = "TestName"
config.per_page = 25
end
assert_equal "TestName", MyModule.config.name
assert_equal 25, MyModule.config.per_page
assert_equal "TestName", MyModule.config[:name]
assert_equal 25, MyModule.config[:per_page]
end
def test_default_values
MyModule.configure do |config|
config.name = "TestName"
end
assert_equal 10, MyModule.config.per_page
end
def test_set_not_exists_attribute
assert_raises NoMethodError do
MyModule.configure do |config|
config.unknown_attribute = "TestName"
end
end
end
def test_get_not_exists_attribute
assert_raises NoMethodError do
MyModule.config.unknown_attribute
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment