module Nocode::Util::Optionable

Add on a DSL for classes. The DSL allows for a new class-level keyword called ‘option’ which can be used to describe what metadata values are important. Then instances can reference those option’s values using magic _option methods. For example:

class Animal

include Optionable
option :type
attr_writer :options

end

animal = Animal.new animal.options = { ‘type’ => ‘dog’ }

animal.type_option # -> should return ‘dog’

Constants

OPTION_PREFIX

Public Class Methods

included(klass) click to toggle source
# File lib/nocode/util/optionable.rb, line 20
def self.included(klass)
  klass.extend(ClassMethods)
end

Public Instance Methods

method_missing(name, *args, &block) click to toggle source
Calls superclass method
# File lib/nocode/util/optionable.rb, line 49
def method_missing(name, *args, &block)
  key = option_key(name)

  if name.to_s.end_with?(OPTION_PREFIX) && self.class.options.include?(key)
    options[key]
  else
    super
  end
end
options() click to toggle source
# File lib/nocode/util/optionable.rb, line 45
def options
  @options || {}
end
respond_to_missing?(name, include_private = false) click to toggle source
Calls superclass method
# File lib/nocode/util/optionable.rb, line 59
def respond_to_missing?(name, include_private = false)
  key = option_key(name)

  (name.to_s.end_with?(OPTION_PREFIX) && self.class.options.include?(key)) || super
end

Private Instance Methods

option_key(name) click to toggle source
# File lib/nocode/util/optionable.rb, line 67
def option_key(name)
  name.to_s.gsub(OPTION_PREFIX, '')
end