Module: IsReviewable::Support

Extended by:
Support
Included in:
Support
Defined in:
lib/is_reviewable/support.rb

Instance Method Summary collapse

Instance Method Details

#hash_conditions_as_array(conditions) ⇒ Object

Hash conditions to array conditions converter, e.g. => value will be turned to: ['key = :key', => value]


44
45
46
# File 'lib/is_reviewable/support.rb', line 44

def hash_conditions_as_array(conditions)
  [conditions.keys.collect { |key| "#{key} = :#{key}" }.join(' AND '), conditions]
end

#is_active_record?(object) ⇒ Boolean

Check if object is a valid activerecord object.


31
32
33
# File 'lib/is_reviewable/support.rb', line 31

def is_active_record?(object)
  object.present? && object.is_a?(::ActiveRecord::Base) # TODO: ::ActiveModel if Rails 3?
end

#is_ip?(object) ⇒ Boolean

Check if input is a valid format of IP, i.e. “#.#.#.#”. Note: Just basic validation.


37
38
39
# File 'lib/is_reviewable/support.rb', line 37

def is_ip?(object)
  (object =~ /^\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}$/) rescue false
end

#polymorphic_conditions_for(object_or_type, field, *match) ⇒ Object

Shortcut method for generating conditions hash for polymorphic belongs_to-associations.


8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/is_reviewable/support.rb', line 8

def polymorphic_conditions_for(object_or_type, field, *match)
  match = [:id, :type] if match.blank?  # Note: {} is equivalent to Hash.new which takes a block, so we must do: ({}) or (Hash.new)

  returning({}) do |conditions|
    conditions.merge!(:"#{field}_id" => object_or_type.id) if object_or_type.is_a?(::ActiveRecord::Base) && match.include?(:id)
    
    if match.include?(:type)
      type = case object_or_type
      when ::Class
        object_or_type.name
      when ::Symbol, ::String
        object_or_type.to_s.singularize.classify
      else # Object - or raise NameError as usual
        object_or_type.class.name
      end
      
      conditions.merge!(:"#{field}_type" => type)
    end
  end
end