module DetectOrCreate::ClassMethods
Public Instance Methods
detect_or_create(args={})
click to toggle source
# File lib/detect_or_create/class_methods.rb, line 3 def detect_or_create(args={}) if errors = invalid_arguments(args) and errors.present? raise StandardError, "#{errors}" end found_object = self.first(:conditions => args[:by]) || self.create(args[:by].merge(args[:with])) if args[:overwrite_existing] && !found_object.new_record? found_object.update_attributes(args[:with]) end found_object end
Private Instance Methods
invalid_arguments(args)
click to toggle source
# File lib/detect_or_create/class_methods.rb, line 38 def invalid_arguments(args) case when missing_keys(args).present? "Missing Arguments: `#{missing_keys(args).join(",")}`" when mismatched_types(args).present? mismatched_types(args) when !args[:by].keys.present? "Missing keys to filter by" end end
mismatched_types(args)
click to toggle source
# File lib/detect_or_create/class_methods.rb, line 32 def mismatched_types(args) required_types.collect { |key, type| "`#{key}` must be a #{type}" if args[key].present? && !args[key].is_a?(type) }.compact.join("\n") end
missing_keys(args)
click to toggle source
# File lib/detect_or_create/class_methods.rb, line 28 def missing_keys(args) required_keys - args.keys end
required_keys()
click to toggle source
# File lib/detect_or_create/class_methods.rb, line 19 def required_keys [:by] end
required_types()
click to toggle source
# File lib/detect_or_create/class_methods.rb, line 23 def required_types { :by => Hash, :with => Hash } end