Sha256: b4517008112d1a8ec02675aa52d30844b85c67cd9ad1b82da920cf92be65627d

Contents?: true

Size: 1.15 KB

Versions: 2

Compression:

Stored size: 1.15 KB

Contents

module DuckPuncher
  class Duck
    attr_accessor :name, :options

    def initialize(name, options = {})
      @name = name
      @options = options
      @punched = false
    end

    # @note Assumes the String duck is loaded first
    def load_path
      path_name = if name == :String
                    name.to_s.downcase
                  else
                    Object.send(:punch, :String, name.to_s).underscore
                  end
      "duck_puncher/ducks/#{path_name}"
    end

    def punch(target = nil)
      if options[:if] && !options[:if].call
        DuckPuncher.log.warn %Q(Failed to punch #{name}!)
        return nil
      end
      options[:before].call if options[:before]
      (target || klass).send :include, DuckPuncher::Ducks.const_get(name)
      options[:after].call if options[:after]
      @punched = true
    end

    def klass
      @klass ||= (options[:class] || name).to_s.split('::').inject(Kernel) { |k, part| k.const_get part }
    end

    def punched?
      @punched
    end

    def delegated
      DelegateClass(klass).tap &method(:punch)
    end

    def classify
      Class.new(klass).tap &method(:punch)
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
duck_puncher-2.6.0 lib/duck_puncher/duck.rb
duck_puncher-2.5.1 lib/duck_puncher/duck.rb