Sha256: f576c0937c0a39c78b95cfa2aa2c5280a2d81b92e10da6de674a8c5f41e31981

Contents?: true

Size: 1.18 KB

Versions: 1

Compression:

Stored size: 1.18 KB

Contents

module Onsi
  class Includes
    attr_reader :included

    def initialize(included)
      @included = parse_included(included)
    end

    def method_missing(name, *args, &block)
      if name =~ /\Afetch_(.*)/
        add_fetch_method(name.to_s.gsub(/\Afetch_/, ''), *args, &block)
      else
        super
      end
    end

    def load_included
      @load_included ||= {}.tap do |root|
        included.each do |name|
          fetcher = fetch_methods[name]
          next if fetcher.nil?

          results = fetcher.call
          root[name] = results
        end
      end
    end

    private

    def fetch_methods
      @fetch_methods ||= {}
    end

    def add_fetch_method(name, &block)
      if block.nil?
        raise ArgumentError, "Must specify a block for fetch_#{name}"
      end

      fetch_methods[name.to_sym] = block
    end

    def parse_included(included)
      case included
      when Enumerable
        included.map(&:to_sym)
      when String
        included.split(',').map(&:to_sym)
      when Symbol
        Array(included)
      when nil
        []
      else
        raise ArgumentError, "Onsi::Includes unknown included type #{included}"
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
onsi-0.8.0 lib/onsi/includes.rb