Sha256: 48db325226905c0313664aa2aceb77df6addadbec43b5fad7d95a35cc0712336

Contents?: true

Size: 1.01 KB

Versions: 5

Compression:

Stored size: 1.01 KB

Contents

module Toy
  module Querying
    extend ActiveSupport::Concern

    module ClassMethods
      def get(id)
        if (attrs = adapter.read(id))
          load(id, attrs)
        end
      end

      def get!(id)
        get(id) || raise(Toy::NotFound.new(id))
      end

      def get_multi(*ids)
        ids.flatten.map { |id| get(id) }
      end

      def get_or_new(id)
        get(id) || new(:id => id)
      end

      def get_or_create(id)
        get(id) || create(:id => id)
      end

      def key?(id)
        adapter.key?(id)
      end
      alias :has_key? :key?

      def load(id, attrs)
        attrs ||= {}
        instance = constant_from_attrs(attrs).allocate
        instance.initialize_from_database(attrs.update('id' => id))
      end

      def constant_from_attrs(attrs)
        return self if attrs.nil?

        type = attrs[:type] || attrs['type']

        return self if type.nil?

        type.constantize
      rescue NameError
        self
      end
      private :constant_from_attrs
    end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
toystore-0.10.4 lib/toy/querying.rb
toystore-0.10.3 lib/toy/querying.rb
toystore-0.10.2 lib/toy/querying.rb
toystore-0.10.1 lib/toy/querying.rb
toystore-0.10.0 lib/toy/querying.rb