Module: OEmbed::Formatter::Base

Included in:
JSON, XML
Defined in:
lib/oembed/formatter/base.rb

Overview

These are methods that are shared by the OEmbed::Formatter sub-classes (i.e. OEmbed::Formatter:JSON and OEmbed::Formatter::XML).

Instance Method Summary (collapse)

Instance Method Details

- (Object) backend=(new_backend)

Given either a String (the name of the backend to use) or an Object (which must respond to the decode method), sets the current backend. Raises a LoadError if the given backend cannot be loaded (e.g. an invalid String name, or the decode method doesn't work properly).

OEmbed::Formatter::XML.backend = 'REXML'
OEmbed::Formatter::JSON.backend = MyCustomJsonDecoder.new


23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/oembed/formatter/base.rb', line 23

def backend=(new_backend)
  new_backend_obj = case new_backend
  when String
    already_required = false
    begin 
      already_required = self::Backends.const_defined?(new_backend, false)
    rescue ArgumentError # we're dealing with ruby < 1.9 where const_defined? only takes 1 argument, but behaves the way we want it to.
      already_required = self::Backends.const_defined?(new_backend)
    rescue NameError # no backends have been loaded yet
      already_required = false
    end

    require "oembed/formatter/#{backend_path}/#{new_backend.downcase}" unless already_required
    self::Backends.const_get(new_backend)
  else
    new_backend
  end
  
  test_backend(new_backend_obj)
  
  @backend = new_backend_obj
  
rescue
  raise LoadError, "There was an error setting the backend: #{new_backend.inspect} - #{$!.message}"
end

- (Object) decode(value)

Parses a String or IO and convert it into an Object



13
14
15
# File 'lib/oembed/formatter/base.rb', line 13

def decode(value)
  backend.decode(value)
end

- (Boolean) supported?

Returns true if there is a valid backend. Otherwise, raises OEmbed::FormatNotSupported



8
9
10
# File 'lib/oembed/formatter/base.rb', line 8

def supported?
  !!backend
end

- (Object) with_backend(new_backend)

Perform a set of operations using a backend other than the current one.

OEmbed::Formatter::XML.with_backend('XmlSimple') do
  OEmbed::Formatter::XML.decode(xml_value)
end


53
54
55
56
57
58
# File 'lib/oembed/formatter/base.rb', line 53

def with_backend(new_backend)
  old_backend, self.backend = backend, new_backend
  yield
ensure
  self.backend = old_backend
end