Sha256: dcacab81d4e86d7c1890d285ef93b89dfc85307f08cb73f8dae3ded2cb7347f8

Contents?: true

Size: 1.98 KB

Versions: 1

Compression:

Stored size: 1.98 KB

Contents

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.to_s.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

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
itrigga-param_fu-0.2.0 lib/trigga/param_fu/param_fu.rb