Sha256: dcabf7876af41a97f0f02624719c4628780e0fe24ccb76ef53476a87fef2fdb9

Contents?: true

Size: 1.33 KB

Versions: 6

Compression:

Stored size: 1.33 KB

Contents

module Lanes
    module Concerns

        # @see ClassMethods
        module RandomHashCode

            extend ActiveSupport::Concern

            # ### Random Hash Code Concern
            # This adds the {#has_random_hash_code} class method
            module ClassMethods

                # A random string that identifies an entity, such as a Customer, or Vendor
                # The code is generated by {Lanes::Strings.random} for new records
                # It's useful for generating *magic* links for access to an entity that cannot be guessed.
                # @param field_name [Symbol] which field should the hash_code be stored in
                # @param length [Integer] how long the hash_code should be

                def has_random_hash_code( field_name: :hash_code, length: 12 )

                    validates field_name, :presence=>{
                        :message=>"hash code is not set (should be automatically chosen)"
                    }

                    scope :with_hash_code, lambda{ | code |
                        where({ :hash_code=>code })
                    }

                    before_validation(:on=>:create) do
                        self[ field_name ] = Lanes::Strings.random( length ) if self[ field_name ].blank?
                    end

                end
            end

        end

    end

end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
lanes-0.1.0 lib/lanes/concerns/random_hash_code.rb
lanes-0.0.8 lib/lanes/concerns/random_hash_code.rb
lanes-0.0.5 lib/lanes/concerns/random_hash_code.rb
lanes-0.0.3 lib/lanes/concerns/random_hash_code.rb
lanes-0.0.2 lib/lanes/concerns/random_hash_code.rb
lanes-0.0.1 lib/lanes/concerns/random_hash_code.rb