module PleaseRun::Configurable

A mixin class that provides 'attribute' to a class. The main use for such attributes is to provide validation for mutators.

Example:

class Person
  include PleaseRun::Configurable

  attribute :greeting, "A simple greeting" do |greeting|
    # do any validation here.
    raise "Greeting must be a string!" unless greeting.is_a?(String)
  end
end

person = Person.new
person.greeting = 1234 # Fails!
person.greeting = "Hello, world!"

puts person.greeting
# "Hello, world!"

Public Class Methods

included(klass) click to toggle source
# File lib/pleaserun/configurable.rb, line 28
def self.included(klass)
  klass.extend(ClassMixin)

  m = respond_to?(:initialize) ? method(:initialize) : nil
  define_method(:initialize) do |*args, &block|
    m.call(*args, &block) if m
    configurable_setup
  end
end

Public Instance Methods

configurable_setup() click to toggle source
# File lib/pleaserun/configurable.rb, line 45
def configurable_setup
  @attributes = {}
  self.class.ancestors.each do |ancestor|
    next unless ancestor.include?(PleaseRun::Configurable)
    ancestor.attributes.each do |facet|
      @attributes[facet.name] = facet.clone
    end
  end
end
validate() click to toggle source
# File lib/pleaserun/configurable.rb, line 38
def validate
  # validate the value of each attribute
  self.class.attributes.each do |attribute|
    attribute.validate(send(attribute.name))
  end
end