Class: CrazyValidators::OEmbedUrlValidator

Inherits:
ActiveModel::EachValidator
  • Object
show all
Defined in:
lib/crazy_validators/o_embed_url_validator.rb

Constant Summary collapse

RESERVED_OPTIONS =
[:type, :success, :maxwidth, :maxheight]
AUTHORIZED_TYPES =
['video', 'link', 'photo', 'rich']

Instance Method Summary collapse

Constructor Details

#initialize(options) ⇒ OEmbedUrlValidator

Returns a new instance of OEmbedUrlValidator.



9
10
11
# File 'lib/crazy_validators/o_embed_url_validator.rb', line 9

def initialize(options)
  super
end

Instance Method Details

#validate_each(record, attribute, value) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/crazy_validators/o_embed_url_validator.rb', line 13

def validate_each(record, attribute, value)
  error_options = options.except(RESERVED_OPTIONS)
  type = [options[:type]].flatten.map(&:to_s).keep_if do |e|
    AUTHORIZED_TYPES.include? e
  end
  oembed_options = options.select do |k,v|
    [:maxwidth, :maxheight].include?(k) && v.is_a?(Fixnum)
  end
  if record.send(attribute.to_s + "_changed?")
    OEmbed::Providers.register_all
    begin
      res = OEmbed::Providers.get(value, oembed_options)
      if type.any? { |t| res.send(t+'?') }
        unless options[:success].nil?
          if options[:success].is_a? Proc
            options[:success].call(res)
          else
            record.send(options[:success].to_sym, res)
          end
        end
      else
        error_options[:required_type] = type.join(", ")
        record.errors.add(attribute, :oembed_not_right_type, error_options)
      end
    rescue OEmbed::Error => e
      record.errors.add(attribute, :oembed_error, error_options)
    end
  end
end