Sha256: 70cbeda13dcc17a6b712490a3242e9a3db798c6c983cab686990f2c187c9d4d4

Contents?: true

Size: 1019 Bytes

Versions: 14

Compression:

Stored size: 1019 Bytes

Contents

module CompositePrimaryKeys
  ID_SEP     = ','
  ID_SET_SEP = ';'

  module ArrayExtension
    def to_composite_keys
      CompositeKeys.new(self)
    end
  end

  def self.normalize(ids)
    ids.map do |id|
      if id.is_a?(Array)
        normalize(id)
      elsif id.is_a?(String) && id.index(ID_SEP)
        id.split(ID_SEP)
      else
        id
      end
    end
  end

  class CompositeKeys < Array

    def self.parse(value)
      case value
      when Array
        value.to_composite_keys
      when String
        self.new(value.split(ID_SEP))
      else
        raise(ArgumentError, "Unsupported type: #{value}")
      end
    end

    def in(other)
      case other
        when Arel::SelectManager
          CompositePrimaryKeys::Nodes::In.new(self, other.ast)
      end
    end


    def to_s
      # Doing this makes it easier to parse Base#[](attr_name)
      join(ID_SEP)
    end
  end
end

Array.send(:include, CompositePrimaryKeys::ArrayExtension)

Version data entries

14 entries across 14 versions & 1 rubygems

Version Path
composite_primary_keys-10.0.5 lib/composite_primary_keys/composite_arrays.rb
composite_primary_keys-9.0.10 lib/composite_primary_keys/composite_arrays.rb
composite_primary_keys-10.0.4 lib/composite_primary_keys/composite_arrays.rb
composite_primary_keys-9.0.9 lib/composite_primary_keys/composite_arrays.rb
composite_primary_keys-10.0.3 lib/composite_primary_keys/composite_arrays.rb
composite_primary_keys-10.0.2 lib/composite_primary_keys/composite_arrays.rb
composite_primary_keys-10.0.1 lib/composite_primary_keys/composite_arrays.rb
composite_primary_keys-9.0.8 lib/composite_primary_keys/composite_arrays.rb
composite_primary_keys-10.0.0 lib/composite_primary_keys/composite_arrays.rb
composite_primary_keys-9.0.7 lib/composite_primary_keys/composite_arrays.rb
composite_primary_keys-9.0.6 lib/composite_primary_keys/composite_arrays.rb
composite_primary_keys-9.0.5 lib/composite_primary_keys/composite_arrays.rb
composite_primary_keys-9.0.4 lib/composite_primary_keys/composite_arrays.rb
composite_primary_keys-9.0.2 lib/composite_primary_keys/composite_arrays.rb