Last active
January 30, 2016 03:27
-
-
Save ridiculous/2a6551966f4aa2a7c17e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Usable | |
def config | |
@config ||= Config.new | |
end | |
def use(mod, options = {}) | |
send :include, mod unless self < mod | |
if block_given? | |
yield config | |
else | |
options.each { |k, v| config.public_send "#{k}=", v } | |
end | |
end | |
class Config < OpenStruct | |
end | |
end | |
# @description TEST CASES | |
=begin | |
module Versionable | |
def versions | |
"Saving #{self.class.config.max_versions} versions to #{self.class.config.table_name}" | |
end | |
end | |
class Model | |
extend Usable | |
# with options hash | |
use Versionable, table_name: 'custom_versions' | |
# or with block | |
use Versionable do |config| | |
config.max_versions = 10 | |
end | |
end | |
Model.config.table_name #=> 'custom_versions' | |
Model.new.versions #=> "Saving 10 versions to custom_versions" | |
=end | |
# | |
# Separate configuration by module name to avoid naming collisions between modules | |
# | |
module Configurable | |
def configs | |
@configs ||= Hash.new do |me, key| | |
me[key] = Config.new | |
end | |
end | |
class Config < OpenStruct | |
end | |
end | |
module Usable | |
def self.extended(base) | |
base.extend Configurable | |
end | |
def use(mod, options = {}) | |
send :include, mod unless self < mod | |
if block_given? | |
yield configs[mod] | |
else | |
options.each { |k, v| configs[mod].public_send "#{k}=", v } | |
end | |
end | |
end | |
# @description TEST CASE | |
=begin | |
module Versionable | |
def versions | |
config = self.class.configs[Versionable] | |
"Saving #{config.max_versions} versions to #{config.table_name}" | |
end | |
end | |
module Notable | |
def notes | |
config = self.class.configs[Notable] | |
"Saving #{config.max_versions} notes to #{config.table_name}" | |
end | |
end | |
class Model | |
extend Usable | |
# with options hash | |
use Versionable, table_name: 'custom_versions' | |
# or with block | |
use Versionable do |config| | |
config.max_versions = 10 | |
end | |
use Notable do |config| | |
config.max_versions = 20 | |
config.table_name = 'custom_notes' | |
end | |
end | |
Model.config.table_name #=> 'custom_versions' | |
Model.new.versions #=> "Saving 10 versions to custom_versions" | |
Model.new.notes #=> "Saving 20 notes to custom_notes" | |
=end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment