require 'hashid/rails/version'
require 'hashids'
require 'active_record'

module Hashid
  module Rails

    # Get configuration or load defaults
    def self.configuration
      @configuration ||= Configuration.new
    end

    # Set configuration settings with a block
    def self.configure
      yield(configuration)
    end

    # Reset gem configuration to defaults
    def self.reset
      @configuration = Configuration.new
    end

    def self.included(base)
      base.extend ClassMethods
    end

    def encoded_id
      self.class.encode_id(id)
    end

    def to_param
      encoded_id
    end
    alias_method :hashid, :to_param

    module ClassMethods

      def hashids
        secret = Hashid::Rails.configuration.secret
        length = Hashid::Rails.configuration.length
        Hashids.new("#{table_name}#{secret}", length)
      end

      def encode_id(id)
        hashids.encode(id)
      end

      def decode_id(id)
        hashids.decode(id.to_s).first
      end

      def find(hashid)
        return super hashid if caller.first(3).any?{|s| s =~ /active_record\/persistence.*reload/}
        super decode_id(hashid) || hashid
      end
    end

    class Configuration
      attr_accessor :secret, :length

      def initialize
        @secret = ''
        @length = 6
      end
    end

  end
end

ActiveRecord::Base.send :include, Hashid::Rails

require 'hashid/rails/version'
require 'hashids'
require 'active_record'

module Hashid
  module Rails

    # Get configuration or load defaults
    def self.configuration
      @configuration ||= Configuration.new
    end

    # Set configuration settings with a block
    def self.configure
      yield(configuration)
    end

    # Reset gem configuration to defaults
    def self.reset
      @configuration = Configuration.new
    end

    def self.included(base)
      base.extend ClassMethods
    end

    def encoded_id
      self.class.encode_id(id)
    end

    def to_param
      encoded_id
    end
    alias_method :hashid, :to_param

    module ClassMethods

      def hashids
        secret = Hashid::Rails.configuration.secret
        length = Hashid::Rails.configuration.length
        Hashids.new("#{table_name}#{secret}", length)
      end

      def encode_id(id)
        hashids.encode(id)
      end

      def decode_id(id)
        hashids.decode(id.to_s).first
      end

      def find(hashid)
        model_reload? ? super(hashid) : super( decode_id(hashid) || hashid )
      end

      private

      def model_reload?
        caller.first(3).any?{|s| s =~ /active_record\/persistence.*reload/}
      end
    end

    class Configuration
      attr_accessor :secret, :length

      def initialize
        @secret = ''
        @length = 6
      end
    end

  end
end

ActiveRecord::Base.send :include, Hashid::Rails

Move the model reload detect regex to help method
Move the model reload detect regex to help method
