Sha256: 6e2ec08bbe6ed66b2a45df30302ddb8e0cb1c455e67b1a2268a5a7e3333e3ae5

Contents?: true

Size: 1.31 KB

Versions: 1

Compression:

Stored size: 1.31 KB

Contents

require "ensurance/version"
require 'active_support'
require 'active_support/core_ext/date'
require 'active_support/core_ext/time'
require 'active_support/core_ext/hash'
require 'json'

require 'ensurance/date'
require 'ensurance/time'
require 'ensurance/hash'

module Ensurance
  extend ActiveSupport::Concern

  class_methods do
    def ensure_by(*args)
      @_ensure_by ||= [:id]
      @_ensure_by += [args].flatten
    end

    def ensure(thing = nil)
      return nil unless thing.present?

      if thing.is_a?(self)
        return thing
      elsif thing.is_a?(GlobalID)
        return GlobalID::Locator.locate(thing)
      elsif thing.is_a?(Hash) && thing['_aj_globalid'] && (found = GlobalID::Locator.locate(thing['_aj_globalid']))
        return found
      elsif thing.is_a?(String) && found = GlobalID::Locator.locate(thing)
        return found
      end
      found = nil

      @_ensure_by ||= [:id]
      @_ensure_by.each do |ensure_field|
        value = thing.try(:fetch, ensure_field.to_sym, nil) || thing.try(:fetch, ensure_field.to_s, nil) || thing
        found = self.find_by(ensure_field => value)
        break if found.is_a?(self)
      end

      found
    end

    def ensure!(thing = nil)
      result = self.ensure(thing)
      raise ::ActiveRecord::RecordNotFound unless result
      result
    end

  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
ensurance-0.1.0 lib/ensurance.rb