Sha256: d736cdbfd5850e4a96dbbe87d1fcb385f387831bc380ece7ce8b98504742cb44

Contents?: true

Size: 1009 Bytes

Versions: 9

Compression:

Stored size: 1009 Bytes

Contents

require "active_model"

module Shamu

  # Adds `to_model_id` to several classes that are often used to look up
  # models by id.
  module ToModelIdExtension

    # Extend common classes to add `to_model_id` method.
    def self.extend!
      Integer.include Integers
      String.include Strings
      Array.include Enumerables

      ActiveRecord::Base.include Models if defined? ActiveRecord::Base
    end

    # Add `to_model_id` to String types.
    module Strings
      NUMERIC_PATTERN = /\A\s*[0-9]+\z/

      def to_model_id
        self =~ NUMERIC_PATTERN ? to_i : nil
      end
    end

    # Add `to_model_id` to Integer types.
    module Integers
      def to_model_id
        self
      end
    end

    # Add `to_model_id` to Enumerable types.
    module Enumerables
      def to_model_id
        map( &:to_model_id )
      end
    end

    # Add `to_model_id` to ActiveModel types.
    module Models
      def to_model_id
        id
      end
    end
  end
end

Shamu::ToModelIdExtension.extend!

Version data entries

9 entries across 9 versions & 1 rubygems

Version Path
shamu-0.0.13 lib/shamu/to_model_id_extension.rb
shamu-0.0.11 lib/shamu/to_model_id_extension.rb
shamu-0.0.9 lib/shamu/to_model_id_extension.rb
shamu-0.0.8 lib/shamu/to_model_id_extension.rb
shamu-0.0.7 lib/shamu/to_model_id_extension.rb
shamu-0.0.5 lib/shamu/to_model_id_extension.rb
shamu-0.0.4 lib/shamu/to_model_id_extension.rb
shamu-0.0.3 lib/shamu/to_model_id_extension.rb
shamu-0.0.2 lib/shamu/to_model_id_extension.rb