Sha256: 86d4f08212027fa6135e6fe0d64b409cb08a500df2e38a2d688bd01d30d140e7

Contents?: true

Size: 1.56 KB

Versions: 1

Compression:

Stored size: 1.56 KB

Contents

require "attr_extras/version"
require "attr_extras/attr_initialize"
require "attr_extras/attr_query"
require "attr_extras/utils"

module AttrExtras
  module ModuleMethods
    def attr_initialize(*names)
      AttrInitialize.new(self, names).apply
    end

    def attr_private(*names)
      # Need this to avoid "private attribute?" warnings when running
      # the full test suite; not sure why exactly.
      public

      attr_reader(*names)
      private(*names)
    end

    def attr_value(*names)
      attr_reader(*names)

      define_method(:==) do |other|
        return false unless other.is_a?(self.class)

        names.all? { |attr| self.public_send(attr) == other.public_send(attr) }
      end

      # Both #eql? and #hash are required for hash identity.

      alias_method :eql?, :==

      define_method(:hash) do
        [self.class, *names.map { |attr| public_send(attr) }].hash
      end
    end

    def pattr_initialize(*names)
      attr_initialize(*names)
      attr_private(*Utils.flat_names(names))
    end

    def vattr_initialize(*names)
      attr_initialize(*names)
      attr_value(*Utils.flat_names(names))
    end

    def method_object(method_name, *names)
      singleton_class.send(:define_method, method_name) do |*values|
        new(*values).send(method_name)
      end

      pattr_initialize(*names)
    end

    def attr_query(*names)
      AttrQuery.define_with_suffix(self, "", *names)
    end

    def attr_id_query(*names)
      AttrQuery.define_with_suffix(self, "_id", *names)
    end
  end
end

class Module
  include AttrExtras::ModuleMethods
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
attr_extras-2.2.2 lib/attr_extras.rb