Sha256: 315cdda6c7ad1cb94768534b4167fee4dafa0dec11e73619622aa51bd76abf3c

Contents?: true

Size: 1.57 KB

Versions: 1

Compression:

Stored size: 1.57 KB

Contents

# frozen_string_literal: true

module LazyRecord
  # This module gives the Base class its functionality, and can be included
  # in any class as an alternative to inheriting from LazyRecord::Base
  module BaseModule
    def self.included(base)
      base.extend(
        ClassMethods,
        Scopes,
        Attributes,
        Associations,
        Callbacks,
        Validations,
        Methods,
        DynamicModules
      )
    end

    attr_writer :id

    def initialize(_opts = {})
      yield self if block_given?
    end

    def instance_attrs_to_s
      []
    end

    def instance_attr_accessors
      []
    end

    def collection_counts_to_s
      []
    end

    def inspect
      "#<#{self.class} id: #{id ? id : 'nil'}"\
      "#{instance_attrs_to_s.unshift('').join(', ')}"\
      "#{collection_counts_to_s.unshift('').join(', ')}>"
    end

    def id
      @id.freeze
    end

    def stringify_value(value)
      if value.is_a?(String)
        "\"#{value}\""
      elsif value.nil?
        'nil'
      else
        value
      end
    end

    private :id=,
            :stringify_value,
            :instance_attrs_to_s,
            :instance_attr_accessors,
            :collection_counts_to_s

    # Class methods provided to all LazyRecord classes
    module ClassMethods
      attr_reader :all

      def count
        @all.count
      end

      def first
        @all.first
      end

      def last
        @all.last
      end

      def where(condition)
        @all.where(condition)
      end

      def destroy_all
        @all.send(:clear)
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
lazy_record-0.1.8 lib/lazy_record/base_module.rb