Sha256: ea81ace0c950083dd772cd94a937bd4da0313286cc98076b051f6f7cf2b21ee2

Contents?: true

Size: 1.78 KB

Versions: 8

Compression:

Stored size: 1.78 KB

Contents

# poorly-optimized, but handy, mixin for Hash and Model examples.
# primarily enables support for lazy values.

module Attributor

  module ExampleMixin

    def self.extended(obj)
      if obj.kind_of? Attributor::Model
        obj.class.attributes.each do |name, _|
          obj.define_singleton_method(name) do
            get(name)
          end
        end
      end
    end

    def lazy_attributes
      @lazy_attributes ||= {}
    end

    def lazy_attributes=(val)
      @lazy_attributes = val
    end

    def [](k)
      unless @contents.key?(k)
        if (proc = lazy_attributes.delete k)
          @contents[k] = proc.call
        end
      end
      @contents[k]
    end

    def []=(k,v)
      lazy_attributes.delete k
      @contents[k] = v
    end

    def each(&block)
      contents.each(&block)
    end

    alias_method :each_pair, :each

    def values
      contents.values
    end

    def empty?
      contents.empty?
    end

    def size
      keys.size
    end

    def keys
      @contents.keys | lazy_attributes.keys
    end

    def key?(key)
      @contents.key?(key) || lazy_attributes.key?(key)
    end

    def get(key, context: self.generate_subcontext(Attributor::DEFAULT_ROOT_CONTEXT,key))
      key = self.class.key_attribute.load(key, context)

      unless @contents.key? key
        if lazy_attributes.key?(key)
          proc = lazy_attributes.delete(key)
          @contents[key] = proc.call(self)
        end
      end

      super
    end

    def attributes
      lazy_attributes.keys.each do |name|
        self.__send__(name)
      end

      super
    end

    def contents
      lazy_attributes.keys.each do |key|
        proc = lazy_attributes.delete(key)
        @contents[key] = proc.call(self) unless @contents.key?(key)
      end

      super
    end
  end

end

Version data entries

8 entries across 8 versions & 1 rubygems

Version Path
attributor-5.0.2 lib/attributor/example_mixin.rb
attributor-5.0.1 lib/attributor/example_mixin.rb
attributor-5.0 lib/attributor/example_mixin.rb
attributor-4.2.0 lib/attributor/example_mixin.rb
attributor-4.1.0 lib/attributor/example_mixin.rb
attributor-4.0.1 lib/attributor/example_mixin.rb
attributor-4.0.0 lib/attributor/example_mixin.rb
attributor-3.0.1 lib/attributor/example_mixin.rb