module Trigga module ParamFu def self.included(base) base.extend(ClassMethods) base.send(:include, InstanceMethods) end module ClassMethods def require_obj_or_id(opts, key) obj_or_id(opts,key) raise ArgumentError.new("#{key} or #{key_with_id(key)} are required") unless opts[key_with_id(key)] opts end def require_param(opts, *keys) keys.to_a.each do |k| raise ArgumentError.new("#{k} is required") unless opts[k] end opts end def obj_or_id(opts, key) opts[key_with_id(key)] ||= opts[key].id if opts[key] end def key_with_id(key) (key.to_s + '_id').to_sym end def require_one_of( opts, *keys ) present = (opts.keys & keys) raise ArgumentError.new( "at least one of the arguments #{keys.inspect} is required" ) if present.empty? return present end def id_or_name_condition(table, val) condition = {:where => nil, :values=>nil} unless val.to_s.empty? unless val.match(/[^0-9]/) condition[:where] = "#{table}.id = ?" condition[:values] = val.to_i else condition[:where] = "#{table}.name LIKE ?" condition[:values] = "#{'%' + val.gsub(/\s*\(\d+\)/,"") + '%'}" end end condition end # fallback when we don't have ActiveSupport's pluralize method available def to_plural(s) (s.match(/[aeiou]$/i) ? s + 's' : s + 'es' ) end end module InstanceMethods def require_obj_or_id(opts,key) self.class.require_obj_or_id(opts, key) end def obj_or_id(opts, key) self.class.obj_or_id(opts, key) end def require_param(opts, *keys) self.class.require_param(opts, *keys) end def require_one_of( opts, *keys ) self.class.require_one_of( opts, *keys ) end end end end