CarrierWave.configure do |config| config.storage = :file config.enable_processing = false end
# configure.rb require 'minitest/autorun' class ConfigurationTest < MiniTest::Test 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 end
➜ Projects ruby configure.rb Run options: --seed 25758 # Running: E Finished in 0.001166s, 857.6329 runs/s, 0.0000 assertions/s. 1) Error: ConfigurationTest#test_configure_block: NameError: uninitialized constant ConfigurationTest::MyModule configure.rb:5:in `test_configure_block' 1 runs, 0 assertions, 0 failures, 1 errors, 0 skips
module MyModule def self.configure end end
module MyModule def self.configure @config ||= {} end def self.config @config end end
require 'minitest/autorun' require 'ostruct' module MyModule def self.configure @config ||= OpenStruct.new yield(@config) if block_given? @config end def self.config @config || configure end end
➜ Projects ruby configure.rb Run options: --seed 8967 # Running: . Finished in 0.001607s, 622.2775 runs/s, 2489.1101 assertions/s. 1 runs, 4 assertions, 0 failures, 0 errors, 0 skips
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
module MyModule CONFIG_ATTRIBUTES = %i(name per_page) def self.configure @config ||= Struct.new(*CONFIG_ATTRIBUTES).new yield(@config) if block_given? @config end def self.config @config || configure end end
def test_default_values MyModule.configure do |config| config.name = "TestName" end assert_equal 10, MyModule.config.per_page end
module ::MyModule def self.reset @config = nil end end def setup MyModule.reset end
self.config ||= begin config = Struct.new(*CONFIG_ATTRIBUTES).new config.per_page = 10 config end
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
module Sample DefaultConfig = Struct.new(:a, :b) do def initialize self.a = 10 self.b = 'test' end end def self.configure @config = DefaultConfig.new yield(@config) if block_given? @config end def self.config @config || configure end end
Source: https://habr.com/ru/post/242729/
All Articles