Sha256: 8f00ac33a5e5684adb1e1fda19be69f2ffff99f69410c3007bc1f622cd50a6d2

Contents?: true

Size: 1.67 KB

Versions: 6

Compression:

Stored size: 1.67 KB

Contents

require 'active_support/core_ext/module'

module Pears
  module Provider
    class Builder
      # Evil meta programming.
      def self.enable_provider(provider, yielder: false)
        method_name = provider.name.split('::').last.underscore.to_sym
        if yielder
          define_method(method_name) do |*args, **opts, &block|
            # Skip if Rails environment should not use this perticular setting
            if defined?(Rails)
              return if Array.wrap(opts[:skip_env]).include?(Rails.env.to_sym)
            end

            pr = provider.new(builder: self, &block)
            push pr
            pr
          end
        else
          define_method(method_name) do |*args, **opts, &block|
            # Skip if Rails environment should not use this perticular setting
            if defined?(Rails)
              return if Array.wrap(opts[:skip_env]).include?(Rails.env.to_sym)
            end

            pr = provider.new(*args, **opts, &block)
            push pr
            pr
          end
        end
      end

      # define Providers
      enable_provider LocalFile
      enable_provider RemoteFile
      enable_provider Subscription, yielder: true

      if defined?(Rails) == "constant"
        enable_provider RailsConfig
      end

      delegate :name, to: :subject

      def initialize(subject)
        @subject = subject
      end

      def freeze_layers
        @skip_push = true
        yield
        @skip_push = false
      end

      def subject_name
        @subject.name
      end

      private

      def push provider
        return provider unless @subject.is_a? Subject

        @subject.push_layer provider unless @skip_push
      end
    end
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
pears-0.3.5 lib/pears/provider/builder.rb
pears-0.3.4 lib/pears/provider/builder.rb
pears-0.3.2 lib/pears/provider/builder.rb
pears-0.3.1 lib/pears/provider/builder.rb
pears-0.3.0 lib/pears/provider/builder.rb
pears-0.2.0 lib/pears/provider/builder.rb