lib/hashid/rails.rb in hashid-rails-0.1.2 vs lib/hashid/rails.rb in hashid-rails-0.2.0
- old
+ new
@@ -2,10 +2,26 @@
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
@@ -16,12 +32,15 @@
encoded_id
end
alias_method :hashid, :to_param
module ClassMethods
+
def hashids
- Hashids.new(table_name, 6)
+ 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
@@ -29,12 +48,28 @@
def decode_id(id)
hashids.decode(id.to_s).first
end
def find(hashid)
- super decode_id(hashid) || hashid
+ model_reload? ? super(hashid) : super( decode_id(hashid) || hashid )
end
+
+ private
+
+ def model_reload?
+ caller.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