Class: OEmbed
- Inherits:
-
Object
- Object
- OEmbed
- Defined in:
- lib/oembed_links.rb,
lib/oembed_links/response.rb,
lib/oembed_links/fetchers/curb.rb,
lib/oembed_links/formatters/json.rb,
lib/oembed_links/fetchers/net_http.rb,
lib/oembed_links/template_resolver.rb,
lib/oembed_links/formatters/lib_xml.rb,
lib/oembed_links/formatters/ruby_xml.rb,
lib/oembed_links/fetchers/ruby_tubesday.rb,
lib/oembed_links/formatters/hpricot_xml.rb
Overview
The class used to represent data returned by the server.
Defined Under Namespace
Modules: Fetchers, Formatters Classes: Response, TemplateResolver
Class Method Summary collapse
-
.autodetect_xml_formatters(*ignore) ⇒ Object
Determine the XML formatter that can be loaded for this system based on what libraries are present.
-
.clear_registrations ⇒ Object
Clear all registration information; really only valuable in testing.
-
.config ⇒ Object
The configuration hash passed into register() or parsed from the YAML file.
-
.get_url_for_provider(url, provider, *attribs) ⇒ Object
Get the OEmbed::Response object for a given URL and provider.
-
.load_default_libs(*ignore_formats) ⇒ Object
Load the default JSON and XML formatters, autodetecting formatters when possible; load the default fetcher as well.
-
.register(config_hash = { }, provider_hash = { }, provider_scheme_hash = { }) ⇒ Object
Configure OEmbed with all necessary information - library configuration, oembed provider urls, and the supported schemes and formats of said providers.
-
.register_fetcher(klass) ⇒ Object
Register a new fetcher.
-
.register_formatter(klass) ⇒ Object
Register a new formatter.
-
.register_provider(provider, url, format = "json", *schemes) ⇒ Object
Register a provider with OEmbed.
-
.register_yaml_file(file) ⇒ Object
Loads the YAML file at the specified path and registers its information with OEmbed.
-
.transform(txt, use_strict = false, *attribs, &block) ⇒ Object
Transform all URLs supported by configured providers by the passed-in block or by outputting their “html” attributes ( or “url” attributes if no “html” attribute exists ).
Class Method Details
.autodetect_xml_formatters(*ignore) ⇒ Object
Determine the XML formatter that can be loaded for this system based on what libraries are present
299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 |
# File 'lib/oembed_links.rb', line 299 def self.autodetect_xml_formatters(*ignore) loaded_lib = false unless ignore.include? "libxml" begin require 'libxml' require 'oembed_links/formatters/lib_xml' self.register_formatter(OEmbed::Formatters::LibXML) loaded_lib = true rescue LoadError puts "Error loading LibXML XML formatter" end end unless loaded_lib || ignore.include?("hpricot") begin require 'hpricot' require 'oembed_links/formatters/hpricot_xml' self.register_formatter(OEmbed::Formatters::HpricotXML) loaded_lib = true rescue LoadError puts "Error loading Hpricot XML formatter" end end unless loaded_lib || ignore.include?("rexml") require 'oembed_links/formatters/ruby_xml' self.register_formatter(OEmbed::Formatters::RubyXML) loaded_lib = true end raise StandardError.new("No XML formatter could be autodetected") unless loaded_lib end |
.clear_registrations ⇒ Object
Clear all registration information; really only valuable in testing
153 154 155 156 157 158 159 |
# File 'lib/oembed_links.rb', line 153 def self.clear_registrations() @schemes = [] @urls = { } @formats = { } @formatters = { } @fetchers = { } end |
.config ⇒ Object
The configuration hash passed into register() or parsed from the YAML file
114 115 116 |
# File 'lib/oembed_links.rb', line 114 def self.config @config end |
.get_url_for_provider(url, provider, *attribs) ⇒ Object
Get the OEmbed::Response object for a given URL and provider. If you wish to pass extra attributes to the provider, provide a hash as the last attribute with keys and values representing the keys and values of the added querystring parameters.
193 194 195 196 197 198 199 200 201 202 203 204 205 206 |
# File 'lib/oembed_links.rb', line 193 def self.get_url_for_provider(url, provider, *attribs) purl = @urls[provider] eurl = CGI.escape(url) purl += (purl.index("?")) ? "&" : "?" purl += "url=#{eurl}" attrib_hash = (attribs.last.is_a?(Hash)) ? attribs.last : { } attrib_hash.each do |k, v| purl += "&#{CGI.escape(k)}=#{CGI.escape(v)}" end fetcher = @fetchers[@fetch_method] || @fetchers[@fetchers.keys.first] formatter = @formatters[@formats[provider]] response = fetcher.fetch(purl) formatter.format(response) end |
.load_default_libs(*ignore_formats) ⇒ Object
Load the default JSON and XML formatters, autodetecting formatters when possible; load the default fetcher as well
163 164 165 166 167 168 169 |
# File 'lib/oembed_links.rb', line 163 def self.load_default_libs(*ignore_formats) self.autodetect_xml_formatters(*ignore_formats) require 'oembed_links/formatters/json' self.register_formatter(OEmbed::Formatters::JSON) require 'oembed_links/fetchers/net_http' self.register_fetcher(OEmbed::Fetchers::NetHTTP) end |
.register(config_hash = { }, provider_hash = { }, provider_scheme_hash = { }) ⇒ Object
Configure OEmbed with all necessary information - library configuration, oembed provider urls, and the supported schemes and formats of said providers.
The configuration hash should follow the form: { :method => “NameOfFetcher” } Note that the name of the fetcher is NOT the classname, but the arbitrarily chosen name provided by that class’ .name() method. By default, it will be NetHTTP.
The provider hash will be a hash where the keys are the symbolic names of the providers, eg. :vimeo, and the values are the URL strings used to query those providers. You may use the substring format inside these URLs to indicate that the given provider URL requires the format desired to be inserted at that point. Whatever format you have configured that provider for in the provider_scheme_hash will be inserted when they are queried.
The provider_scheme_hash is a hash with two keys - the first key is the format key, which will either be the string “json” or the string “xml”. The other key will be the schemes key, which contains an array of supported URL schemes by the provider.
It is assumed that all hashes passed in use symbols for keys. Do not use string keys. This decision is totally arbitrary and without any technical merit.
It is assumed that all provider names are symbols. Same rules as above.
101 102 103 104 105 106 107 108 109 110 111 |
# File 'lib/oembed_links.rb', line 101 def self.register(config_hash = { }, provider_hash = { }, provider_scheme_hash = { }) @fetch_method = (config_hash[:method] || "NetHTTP") @config = config_hash provider_hash.each do |provider, url| config = provider_scheme_hash[provider] raise "No Schemes were provided for #{provider.to_s}" if config.nil? || config[:schemes].nil? || config[:schemes].empty? self.register_provider(provider, url, config[:format] || "json", *config[:schemes]) end end |
.register_fetcher(klass) ⇒ Object
Register a new fetcher. klass is the class object of the desired fetcher. A new instance of klass will be created and stored. This instance MUST respond to the methods “name” and “fetch”.
183 184 185 186 187 |
# File 'lib/oembed_links.rb', line 183 def self.register_fetcher(klass) @fetchers ||= { } inst = klass.new @fetchers[inst.name] = inst end |
.register_formatter(klass) ⇒ Object
Register a new formatter. klass is the class object of the desired formatter. A new instance of klass will be created and stored. This instance MUST respond to the methods “name” and “format”.
174 175 176 177 178 |
# File 'lib/oembed_links.rb', line 174 def self.register_formatter(klass) @formatters ||= { } inst = klass.new @formatters[inst.name] = inst end |
.register_provider(provider, url, format = "json", *schemes) ⇒ Object
Register a provider with OEmbed. The provider name should be a symbol, like :flickr. The URL should be a string representing the endpoint for that provider, and may include the format substring to indicate how that provider should be notified of the desired format. format is either the string “json”, or the string “xml”. The list of schemes is an array of strings representing the different URL schemes supported by the provider. These strings follow the form:
http://.somedomain.//
All schemes should use * to indicate variable text matched until the next non-* character or end of line.
130 131 132 133 134 135 136 137 138 139 140 141 |
# File 'lib/oembed_links.rb', line 130 def self.register_provider(provider, url, format = "json", *schemes) @schemes ||= [ ] @urls ||= { } @formats ||= { } @formats[provider] = format @urls[provider] = url.gsub(/\{format\}/i, format) schemes.each do |scheme| sanitized_scheme = scheme.gsub(/([\.\?])/) { |str| "\\#{$1}" }.gsub(/\*/, '.+?') @schemes << [Regexp.new("^" + sanitized_scheme + "$"), provider] end end |
.register_yaml_file(file) ⇒ Object
Loads the YAML file at the specified path and registers its information with OEmbed.
145 146 147 148 149 150 |
# File 'lib/oembed_links.rb', line 145 def self.register_yaml_file(file) y = YAML.load(File.read(file)) self.register(y.delete(:config), y.delete(:providers), y) end |
.transform(txt, use_strict = false, *attribs, &block) ⇒ Object
Transform all URLs supported by configured providers by the passed-in block or by outputting their “html” attributes ( or “url” attributes if no “html” attribute exists ). You may pass in a hash to specify extra parameters that should be appended to the querystrings to any matching providers (see OEmbed.get_url_for_provider). If you pass a block to this method, that block will be executed for each URL found in txt that has a matching provider. This block will be passed the OEmbed::Response object representing the embedding information for that url.
OEmbed.transform supports two additional parameters:
use_strict: Optionally use Ruby's stricter URI detection regex. While
this will be technically correct regex, not all URLs
use correct syntax. If this is false, URLs will be detected
by the incredibly naive approach of finding any instance of
http:// or https://, and finding anything that is not whitespace
after that.
Example:
OEmbed.transform("all my urls are correctly formed", true)
(options hash): This hash is used to append extra querystring parameters
to the oembed provider. For example:
OEmbed.transform("blah", false, :max_width => 320, :max_height => 200)
You may fine tune the appearance of the embedding information by using the following forms:
OEmbed.transform(some_string) do |r, url|
r.from?(:provider_name) { |content| content["html"] }
r.matches?(/some_regex_against_the_url/) { |content| content["title"] }
r.video?(:template => "videos/oembed_link")
r.audio? { |audio| content["html"] }
r.hedgehog?(:template => File.join(File.dirname(__FILE__), "templates", "hedgehogs.haml"))
r.photo? { |photo| "<img src='#{photo["url"]}' title='#{photo['title']} />" }
r.any? { |anythingelse| content["title"] }
end
The priority of these conditions is as follows:
The first matching block for provider (.from?(:provider_name)) takes precendence OVER
The first matching block for a URL regex (.matches?(/some_regex_against_the_url/)) takes precedence OVER
The first matching block for a type equivalent (.video?, .audio?, .hedgehog?, .photo?) takes precendence OVER
The match anything block (.any?)
You do not need to specify an .any? block if you do not intend to perform any special transformations upon its data; the OEmbed::Response object will output either its html attribute (if it exists) or its url attribute.
The value passed to these conditional blocks is a hash representing the data returned by the server. The keys of all the attributes will be strings.
If you specify the :template option, a template will be found for you based on your current engironment. Currently there is support for Haml, Erubis and ERB templates. Each template will have the following local variables available to it:
url : The URL for which OEmbed data exists
data : A hash of the actual OEmbed data for that URL
response : The OEmbed::Response object for the URL
If you are using Rails, you may specify your template relative to your application’s view root (eg “photos/flickr_oembed”), and your template will be found based on your application settings. For more options regarding template support, see the documentation for OEmbed::TemplateResolver.
NOTE: The type equivalent blocks (.video?, .audio?, .hedgehog?, .photo?, etc.) perform an equality test between the method name and the type returned by the OEmbed provider. You may specify any type name you wish as the method name, and its type will be checked appropriately (as shown by the obviously trivial .hedgehog? method name).
281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 |
# File 'lib/oembed_links.rb', line 281 def self.transform(txt, use_strict = false, *attribs, &block) ret = txt.dup if use_strict URI.extract(txt, "http") do |u| transform_url_for_text!(u, ret, *attribs, &block) end else simple_extract(txt) do |u| transform_url_for_text!(u, ret, *attribs, &block) end end return ret end |