migrated flashobject_helper to swf_fu because the first is not maintained anymore. Fixes #796

This commit is contained in:
Reinier Balt 2010-07-29 21:41:36 +02:00
parent bb23a4acba
commit 65ecb7b019
26 changed files with 737 additions and 158 deletions

View file

@ -9,7 +9,7 @@
'jquery.blockUI','jquery.jeditable','jquery.autocomplete',
'jquery.truncator', :cache => 'jquery-all' %>
<%= javascript_include_tag 'hoverIntent','superfish','application',
'accesskey-hints','niftycube','flashobject', :cache => 'tracks' %>
'accesskey-hints','niftycube','swfobject', :cache => 'tracks' %>
<%= javascript_tag "var AUTH_TOKEN = #{form_authenticity_token.inspect};" if protect_against_forgery? %>
<%= javascript_tag "var SOURCE_VIEW = '#{@source_view}';" %>
<%= javascript_tag "var TAG_NAME = '#{@tag_name}';" if @tag_name %>

View file

@ -1 +1,6 @@
<%= flashobject_tag "open-flash-chart.swf", :query_params => { 'width' => width, 'height' => height, 'data' => data}, :size => "#{width}x#{height}", :parameters => { 'allowScriptAccess' => 'sameDomain', 'wmode' => 'transparent'}, :class_name => 'open-flash-chart', :flash_id => 'chart' %>
<% @swf_count ||= 0 -%>
<div class="open-flash-chart"><%= swf_tag "open-flash-chart.swf",
:flashvars => { 'width' => width, 'height' => height, 'data' => data},
:parameters => { 'allowScriptAccess' => 'sameDomain', 'wmode' => 'transparent'},
:div_id => "chart_#{@swf_count+=1}",
:size => "#{width}x#{height}" %></div>

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

BIN
public/swfs/expressInstall.swf Executable file

Binary file not shown.

View file

View file

@ -1,35 +0,0 @@
FlashObject v.1.0
====================
This FlashObject Helper is based on the flash view helper of the plugin http://laszlo-plugin.rubyforge.org/
It's only copy the FlashObject.js (version 1.5) on your public/javascript directory and register it in the AssetTagHelper of rails,
so for include the javascript in your page you only can add this (if you havn't yet):
<%= javascript_include_tag :defaults %>
or if you only need the flashobject add this:
<%= javascript_include_tag "flashobject" %>
The is very simple for add a Flash in your page add this:
<%= flashobject_tag "/source/of/your/flash.swf" %>
It's simple.
You can add some options if you want:
- div_id: the HTML +id+ of the +div+ element that is used to contain the Flash object; default "flashcontent"
- flash_id: the +id+ of the Flash object itself.
- background_color: the background color of the Flash object; default white
- flash_version: the version of the Flash player that is required; default "7"
- size: the size of the Flash object, in the form "100x100". Defaults to "100%x100%"
- variables: a Hash of initialization variables that are passed to the object; default <tt>{:lzproxied => false}</tt>
- parameters: a Hash of parameters that configure the display of the object; default <tt>{:scale => 'noscale'}</tt>
- fallback_html: HTML text that is displayed when the Flash player is not available.
Example:
<%= flashobject_tag "/source/of/your/flash.swf", :size => "350x320" %>
Vist my website: http://blog.lipsiasoft.com

View file

@ -1,4 +0,0 @@
# Author:: Davide D'Agostino Aka DAddYE
# WebSite:: http://www.lipsiasoft.com
require 'flashobject_view_helper'

View file

@ -1,5 +0,0 @@
require 'fileutils'
flashobject = File.dirname(__FILE__) + '/../../../public/javascripts/flashobject.js'
FileUtils.cp File.dirname(__FILE__) + '/javascripts/flashobject.js', flashobject unless File.exist?(flashobject)
puts IO.read(File.join(File.dirname(__FILE__), 'README'))

File diff suppressed because one or more lines are too long

View file

@ -1,96 +0,0 @@
# Author:: Davide D'Agostino aka DAddYE
# WebSite:: http://www.lipsiasoft.com
require 'action_view'
module ActionView #:nodoc:
module Helpers # :nodoc:
module FlashObjectHelper # :nodoc:
def self.included(base)
base.class_eval do
include InstanceMethods
end
end
module InstanceMethods
# Returns a set of tags that display a Flash object within an
# HTML page.
#
# Options:
# * <tt>:div_id</tt> - the HTML +id+ of the +div+ element that is used to contain the Flash object; default "flashcontent"
# * <tt>:flash_id</tt> - the +id+ of the Flash object itself.
# * <tt>:background_color</tt> - the background color of the Flash object; default white
# * <tt>:flash_version</tt> - the version of the Flash player that is required; default "7"
# * <tt>:size</tt> - the size of the Flash object, in the form "100x100". Defaults to "100%x100%"
# * <tt>:variables</tt> - a Hash of initialization variables that are passed to the object; default <tt>{:lzproxied => false}</tt>
# * <tt>:parameters</tt> - a Hash of parameters that configure the display of the object; default <tt>{:scale => 'noscale'}</tt>
# * <tt>:fallback_html</tt> - HTML text that is displayed when the Flash player is not available.
#
# The following options are for developers. They default to true in
# development mode, and false otherwise.
# * <tt>:check_for_javascript_include</tt> - if true, the return value will cause the browser to display a diagnostic message if the FlashObject JavaScript was not included.
# * <tt>:verify_file_exists</tt> - if true, the return value will cause the browser to display a diagnostic message if the Flash object does not exist.
#
# (This method is called flashobject_tag instead of flashobject_tag
# because it returns a *sequence* of HTML tags: a +div+, followed by
# a +script+.)
def flashobject_tag source, options={}
source = flash_path(source)
query_params = '?' + options[:query_params].map{ |key, value| "#{key}=#{value}" }.join('&') if options[:query_params]
div_id = options[:div_id] || "flashcontent_#{rand(1_100)}"
flash_id = options[:flash_id] || File.basename(source, '.swf') + "_#{rand(1_100)}"
width, height = (options[:size]||'100%x100%').scan(/^(\d*%?)x(\d*%?)$/).first
background_color = options[:background_color] || '#ffffff'
flash_version = options[:flash_version] || 7
class_name = options[:class_name] || 'flash'
variables = options.fetch(:variables, {})
parameters = options.fetch(:parameters, {:scale => 'noscale'})
fallback_html = options[:fallback_html] || %q{<p>Requires the Flash plugin. If the plugin is already installed, click <a href="?detectflash=false">here</a>.</p>}
if options.fetch(:check_for_javascript_include, ENV['RAILS_ENV'] == 'development')
check_for_javascript ="if (typeof FlashObject == 'undefined') document.getElementById('#{div_id}').innerHTML = '<strong>Warning:</strong> FlashObject is undefined. Did you forget to execute <tt>rake update_javascripts</tt>, or to include <tt>&lt;%= javascript_include_tag :defaults %></tt> in your view file?';"
end
return <<-"EOF"
<div id="#{div_id}" class="#{class_name}" style="height: #{height}">
#{fallback_html}
</div>
<script type="text/javascript">//<![CDATA[
#{check_for_javascript}
var fo = new FlashObject("#{source}#{query_params}", "#{flash_id}", "#{width}", "#{height}", "#{flash_version}", "#{background_color}");
#{parameters.map{|k,v|%Q[fo.addParam("#{k}", "#{v}");]}.join("\n")}
#{variables.map{|k,v|%Q[fo.addVariable("#{k}", "#{v}");]}.join("\n")}
fo.write("#{div_id}");
//]]>
</script>
EOF
end
# Computes the path to a flash asset in the public swf directory.
# If the +source+ filename has no extension, .swf will be appended.
# Full paths from the document root will be passed through.
#
# flash_path "movie" # => /swf/movie.swf
# flash_path "dir/movie.swf" # => /swf/dir/movie.swf
# flash_path "/dir/movie" # => /dir/movie.swf
def flash_path(source)
#BROKEN IN RAILS 2.2 -- code below hacked in pending a refresh of this plugin or change to another --luke@lukemelia.com
#compute_public_path(source, 'swf', 'swf', false)
dir = "/swf/"
if source !~ %r{^/}
source = "#{dir}#{source}"
end
relative_url_root = ActionController::Base.relative_url_root
if source !~ %r{^#{relative_url_root}/}
source = "#{relative_url_root}#{source}"
end
source
end
end
end
end
end
ActionView::Base.class_eval do
include ActionView::Helpers::FlashObjectHelper
end
ActionView::Helpers::AssetTagHelper.register_javascript_include_default 'flashobject'

46
vendor/plugins/swf_fu/CHANGELOG.rdoc vendored Normal file
View file

@ -0,0 +1,46 @@
= swf_fu --- History
== Version 1.4.0 - May 8, 2010
* Any option can be a block, in which case it is called (with the source swf passed as argument)
== Version 1.3.1 - February 5, 2010
* Improved compatibility with Rails 3.0: swf_tag now outputs html_safe content.
* Got rid of deprecation warning in Rails 2.2+ when using swf_tag in block form.
== Version 1.3.0 - June 20, 2009
* Updated to swf_object v2.2. Change should not be noticeable to users, except compatibility improvements and better auto install. Added the option +switch_off_auto_hide_show+.
== Version 1.2.0 - January 14, 2009
* flashvars[:id] will now default to the DOM id of the object. I didn't want to have any extra defaults than the very basic ones, but there is no easy way to get this from Flash (see http://www.actionscript.org/forums/showthread.php3?t=136044 ) and no easy way to specify that using +swf_default_options+.
* If flashvars is a string (e.g. "myVar=myValue") it will be parsed into a hash so that the behaviour for default values apply to strings or hashes. swf_default_options[:flashvars] can also be a string and will also be parsed before being merged.
* Small bug fix: the options passed as hashes (:flashvars, :parameters and :html_options) were changed if swf_default_options[:flashvars, ...] existed. They are now left unchanged.
== Version 1.1.0 - January 3, 2009
* Improved the way to specify alternate content
== Version 1.0.3 - January 3, 2009
* Improved javascript initialization
:initialize => [1, 2, 3] # produces in javascript: obj.initialize(1,2,3) instead of ([1,2,3])
# no :initialize produces in javascript: obj.initialize() instead of (null)
:initialize => nil # stil produces obj.initialize(null)
== Version 1.0.2 - January 3, 2009
* Bug fix for flashvars in dynamic method
== Version 1.0.1 - January 2, 2009
* File reorganization
* Bug fix for default options
== Version 1.0 - X-mas, 2008
=== Initial release.

31
vendor/plugins/swf_fu/FLASH_OBJECT.rdoc vendored Normal file
View file

@ -0,0 +1,31 @@
== Compatibility with FlashObject
This document is intended for users of FlashObject, a (much older) swf embedding plugin that inspired swf_fu.
You can choose to:
1) keep both. They won't interfere and +flashobject_tag+ will continue to use the older SWFObject 1.5 library.
2) remove FlashObject:
script/plugin remove flashobject_helper
You can also manually remove <tt>javascripts/flashobject.js</tt>
+swf_fu+ will take over the +flashobject_tag+ and will use the new SWFObject 2.2 library.
This should not have impacts as long as:
* your swf path is absolute (e.g. "/path/to/my_flash.swf"). If it is relative, move your swf file from 'public/' to the new 'public/swfs/' asset folder
* you include the default javascripts (otherwise you need to include 'swfobject' explicitely and stop including 'flashobject')
* you don't use the javascript object before the page is loaded. SWFObject 2.2 makes the changes to the web page later
* you don't rely on the +verify_file_exists+ option (it doesn't do anything anymore)
In either case 1 or 2, you change existing calls to +flashobject_tag+ for +swf_tag+ at your leisure.
The interface is similar and the main differences are some options name changes:
:flash_id => :id
:variables => :flashvars
:background_color => options[:parameters][:bgcolor]
Moreover, the following defaults are gone:
:flashvars[:lzproxied]
:parameters[:scale]
:parameters[:bgcolor]

29
vendor/plugins/swf_fu/LICENSE vendored Normal file
View file

@ -0,0 +1,29 @@
# swf_fu plugin for rails
# Copyright (c) 2010, Marc-André Lafortune.
# All rights reserved.
# Inspired by FlashObject by Davide D'Agostino aka DAddYE (http://www.lipsiasoft.com)
# Uses SWFObject.js 2.1 (http://code.google.com/p/swfobject)
#
# Licensed under the terms of the (modified) BSD License below:
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the <organization> nor the
# names of its contributors may be used to endorse or promote products
# derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''AS IS'' AND ANY
# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

91
vendor/plugins/swf_fu/README.rdoc vendored Normal file
View file

@ -0,0 +1,91 @@
= +swf_fu+
With the +swf_fu+ plugin, rails treats your swf files like any other asset (images, javascripts, etc...).
+swf_fu+ (pronounced "swif-fu", bonus joke for french speakers) uses SWFObject 2.2 to embed swf objects in HTML and supports all its options.
SWFObject 2 is such a nice library that Adobe now uses it as the official way to embed swf!
SWFObject's project can be found at http://code.google.com/p/swfobject
+swf_fu+ has been tested with rails v2.0 up to v3.0b and has decent test coverage so <tt>rake test:plugins</tt> should reveal any incompatibility. Comments and pull requests welcome: http://github.com/marcandre/swf_fu
== Install
Assuming you have git[http://git-scm.com/] installed (check with <tt>git version</tt>), it is easy to install from your applications directory:
rails plugin install git://github.com/marcandre/swf_fu.git # rails 3
script/plugin install git://github.com/marcandre/swf_fu.git # rails 2 (starting at 2.0.2)
For older versions of +rails+ or without +git+, you can always download
+swf_fu+ from github[http://github.com/marcandre/swf_fu/archives/master] and then install it manually:
rails plugin install ~/Download/swf_fu # rails 3
script/plugin install ~/Downloads/swf_fu # rails 2.x
== Usage
=== Embedding in HTML
To embed a swf file, use +swf_tag+:
<%= swf_tag "i_like_flashing" %>
Exactly like images and javascripts, +swf_tag+ will use +swf_path+
to determine the path of the swf file; it will assume it is in <tt>/public/swfs/</tt>
unless specified otherwise and it will add the ".swf" extension automatically.
You can specify alternate content either with the options <tt>:alt => "Get Flash!"</tt> or you can use +swf_tag+ as a block:
<% swf_tag "i_like_flashing" do %>
Get Flash
<% end %>
=== Options
* <tt>:id</tt> - the DOM +id+ of the flash +object+ element that is used to contain the Flash object; defaults to the name of the swf in +source+
* <tt>:width, :height</tt> - the width & height of the Flash object. Defaults to "100%". These could also specified using :size
* <tt>:size</tt> - the size of the Flash object, in the form "400x300".
* <tt>:mode</tt> - Either :dynamic (default) or :static. Refer to SWFObject's doc[http://code.google.com/p/swfobject/wiki/documentation#Should_I_use_the_static_or_dynamic_publishing_method?]
* <tt>:flashvars</tt> - a Hash of variables that are passed to the swf. Can also be a string like <tt>"foo=bar&hello=world"</tt>. Defaults to <tt>{:id => the DOM id}</tt>
* <tt>:parameters</tt> - a Hash of configuration parameters for the swf. See Adobe's doc[http://kb.adobe.com/selfservice/viewContent.do?externalId=tn_12701#optional]
* <tt>:alt</tt> - HTML text that is displayed when the Flash player is not available. Defaults to a "Get Flash" image pointing to Adobe Flash's installation page. This can also be specified as a block (see embedding section). In Rails 3, this text is _assumed_ to be HTML, so there is no need to call +html_safe+ on it.
* <tt>:flash_version</tt> - the version of the Flash player that is required (e.g. "7" (default) or "8.1.0")
* <tt>:auto_install</tt> - a swf file that will upgrade flash player if needed (defaults to "expressInstall" which was installed by +swf_fu+)
* <tt>:javascript_class</tt> - specify a javascript class (e.g. "MyFlash") for your flash object. If it exists, the initialize method will be called.
* <tt>:initialize</tt> - arguments to pass to the initialization method of your javascript class.
* <tt>:div_id</tt> - the DOM +id+ of the containing div itself. Defaults to <tt>"#{option[:id]}_div"</tt>
* <tt>:switch_off_auto_hide_show</tt> - switch off SWFObject's default hide/show behavior. SWFObject temporarily hides your SWF or alternative content until the library has decided which content to display. Defaults to nil.
You can override these default options with a global setting:
ActionView::Base.swf_default_options = {:mode => :static} # All swf_tag will use the static mode by default
Any of these options can be a +Proc+, in which case it will be called each time swf_tag is called.
For example, the following will generate unique IDs:
my_swf_counter = 0
ActionView::Base.swf_default_options[:id] = Proc.new{"swf_unique_id_#{my_swf_counter+=1}"}
=== Javascript
+swf_fu+ will add 'swfobject' to the list of default javascript files. If you don't include
the default javascripts, a simple <tt>javascript_include "swfobject"</tt> is needed.
=== swf_path
+swf_tag+ implements and relies on +swf_path+ which behaves in a similar fashion to +image_path+, +javascript_path+, etc...:
swf_path("example") => "/swfs/example.swf"
swf_path("example.swf") => "/swfs/example.swf"
swf_path("fonts/optima") => "/swfs/fonts/optima.swf"
swf_path("/fonts/optima") => "/fonts/optima.swf"
swf_path("http://www.example.com/game.swf") => "http://www.example.com/game.swf"
It takes into account the global setting +asset_host+, like any other asset:
ActionController::Base.asset_host = "http://assets.example.com"
image_path("logo.jpg") => "http://assets.example.com/images/logo.jpg"
swf_path("fonts/optima") => "http://assets.example.com/swfs/fonts/optima.swf""
Copyright (c) 2010 Marc-André Lafortune, released under the BSD license

22
vendor/plugins/swf_fu/Rakefile vendored Normal file
View file

@ -0,0 +1,22 @@
require 'rake'
require 'rake/testtask'
require 'rake/rdoctask'
desc 'Default: run unit tests.'
task :default => :test
desc 'Test the swf_fu plugin.'
Rake::TestTask.new(:test) do |t|
t.libs << 'lib'
t.pattern = 'test/**/*_test.rb'
t.verbose = true
end
desc 'Generate documentation for the swf_fu plugin.'
Rake::RDocTask.new(:rdoc) do |rdoc|
rdoc.rdoc_dir = 'rdoc'
rdoc.title = 'Swf Fu'
rdoc.options << '--line-numbers' << '--inline-source' << '-m README.rdoc'
rdoc.rdoc_files.include('*.rdoc')
rdoc.rdoc_files.include('lib/**/*.rb')
end

File diff suppressed because one or more lines are too long

Binary file not shown.

10
vendor/plugins/swf_fu/init.rb vendored Normal file
View file

@ -0,0 +1,10 @@
require 'action_view/helpers/asset_tag_helper'
require File.dirname(__FILE__) + "/lib/action_view/helpers/swf_fu_helper"
require File.dirname(__FILE__) + "/lib/action_view/helpers/asset_tag_helper/swf_asset"
# ActionView::Helpers is for recent rails version, ActionView::Base for older ones (in which case ActionView::Helpers::AssetTagHelper is also needed for tests...)
ActionView::Helpers.class_eval { include ActionView::Helpers::SwfFuHelper } # For recent rails version...
ActionView::Base.class_eval { include ActionView::Helpers::SwfFuHelper } # ...and for older ones
ActionView::TestCase.class_eval { include ActionView::Helpers::SwfFuHelper } if defined? ActionView::TestCase # ...for tests in older versions
ActionView::Helpers::AssetTagHelper.register_javascript_include_default 'swfobject'

24
vendor/plugins/swf_fu/install.rb vendored Normal file
View file

@ -0,0 +1,24 @@
require "fileutils"
# Some paths
src = File.dirname(__FILE__)+"/assets"
dest = File.dirname(__FILE__)+"/../../../public"
filename = "#{dest}/javascripts/swfobject.js"
unless File.exist?(filename)
FileUtils.cp "#{src}/javascripts/swfobject.js", filename
puts "Copying 'swfobject.js'"
end
unless File.exist?("#{dest}/swfs/")
FileUtils.mkdir "#{dest}/swfs/"
puts "Creating new 'swfs' directory for swf assets"
end
filename = "#{dest}/swfs/expressInstall.swf"
unless File.exist?(filename)
FileUtils.cp "#{src}/swfs/expressInstall.swf", filename
puts "Copying 'expressInstall.swf', the default flash auto-installer."
end
puts "Installation done."

View file

@ -0,0 +1,61 @@
module ActionView #:nodoc:
# <tt>ActionView::Base.swf_default_options</tt> is a hash that
# will be used to specify defaults in priority to the standard
# defaults.
class Base
@@swf_default_options = {}
cattr_accessor :swf_default_options
end
module Helpers # :nodoc:
module AssetTagHelper
# Computes the path to an swf asset in the public 'swfs' directory.
# Full paths from the document root will be passed through.
# Used internally by +swf_tag+ to build the swf path.
#
# ==== Examples
# swf_path("example") # => /swfs/example.swf
# swf_path("example.swf") # => /swfs/example.swf
# swf_path("fonts/optima") # => /swfs/fonts/optima.swf
# swf_path("/fonts/optima") # => /fonts/optima.swf
# swf_path("http://www.example.com/game.swf") # => http://www.example.com/game.swf
#
# It takes into account the global setting +asset_host+, like any other asset:
#
# ActionController::Base.asset_host = "http://assets.example.com"
# image_path("logo.jpg") # => http://assets.example.com/images/logo.jpg
# swf_path("fonts/optima") # => http://assets.example.com/swfs/fonts/optima.swf
#
def swf_path(source)
if defined? SwfTag
SwfTag.new(self, @controller, source).public_path
else
compute_public_path(source, SwfAsset::DIRECTORY, SwfAsset::EXTENSION)
end
end
alias_method :path_to_swf, :swf_path # aliased to avoid conflicts with a swf_path named route
private
module SwfAsset # :nodoc:
DIRECTORY = 'swfs'.freeze
EXTENSION = 'swf'.freeze
def directory
DIRECTORY
end
def extension
EXTENSION
end
end
# AssetTag is available since 2.1.1 (http://github.com/rails/rails/commit/900fd6eca9dd97d2341e89bcb27d7a82d62965bf )
class SwfTag < AssetTag # :nodoc:
include SwfAsset
end if defined? AssetTag
end
end
end

View file

@ -0,0 +1,188 @@
module ActionView #:nodoc:
module Helpers # :nodoc:
module SwfFuHelper
# Returns a set of tags that display a Flash object within an
# HTML page.
#
# Options:
# * <tt>:id</tt> - the DOM +id+ of the flash +object+ element that is used to contain the Flash object; defaults to the name of the swf in +source+
# * <tt>:width, :height</tt> - the width & height of the Flash object. Defaults to "100%". These could also specified using :size
# * <tt>:size</tt> - the size of the Flash object, in the form "400x300".
# * <tt>:mode</tt> - Either :dynamic (default) or :static. Refer to SWFObject's doc[http://code.google.com/p/swfobject/wiki/documentation#Should_I_use_the_static_or_dynamic_publishing_method?]
# * <tt>:flashvars</tt> - a Hash of variables that are passed to the swf. Can also be a string like <tt>"foo=bar&hello=world"</tt>
# * <tt>:parameters</tt> - a Hash of configuration parameters for the swf. See Adobe's doc[http://kb.adobe.com/selfservice/viewContent.do?externalId=tn_12701#optional]
# * <tt>:alt</tt> - HTML text that is displayed when the Flash player is not available. Defaults to a "Get Flash" image pointing to Adobe Flash's installation page.
# * <tt>:flash_version</tt> - the version of the Flash player that is required (e.g. "7" (default) or "8.1.0")
# * <tt>:auto_install</tt> - a swf file that will upgrade flash player if needed (defaults to "expressInstall" which was installed by swf_fu)
# * <tt>:javascript_class</tt> - specify a javascript class (e.g. "MyFlash") for your flash object. The initialize method will be called when the flash object is ready.
# * <tt>:initialize</tt> - arguments to pass to the initialization method of your javascript class.
# * <tt>:div_id</tt> - the DOM +id+ of the containing div itself. Defaults to <tt>"#{option[:id]}"_div</tt>
#
def swf_tag(source, options={}, &block)
Generator.new(source, options, self).generate(&block)
end
# For compatibility with the older FlashObject.
# It modifies the given options before calling +swf_tag+.
# See FLASH_OBJECT.rdoc
def flashobject_tag_for_compatibility(source, options={})
options = options.reverse_merge(
:auto_install => nil,
:parameters => {:scale => "noscale"},
:variables => {:lzproxied => false},
:flash_id => "flashcontent_#{rand(1_100)}",
:background_color => "#ffffff"
)
{ :variables => :flashvars, :flash_id => :id }.each{|from, to| options[to] ||= options.delete(from) }
options[:parameters][:bgcolor] ||= options.delete(:background_color)
swf_tag(source, options)
end
alias_method :flashobject_tag, :flashobject_tag_for_compatibility unless defined? flashobject_tag
private
DEFAULTS = {
:width => "100%",
:height => "100%",
:flash_version => 7,
:mode => :dynamic,
:auto_install => "expressInstall",
:alt => <<-"EOS".squeeze(" ").strip.freeze
<a href="http://www.adobe.com/go/getflashplayer">
<img src="http://www.adobe.com/images/shared/download_buttons/get_flash_player.gif" alt="Get Adobe Flash player" />
</a>
EOS
}.freeze
class Generator # :nodoc:
VALID_MODES = [:static, :dynamic]
def initialize(source, options, view)
@view = view
@source = view.swf_path(source)
options = ActionView::Base.swf_default_options.merge(options)
options.each do |key, value|
options[key] = value.call(source) if value.respond_to?(:call)
end
[:html_options, :parameters, :flashvars].each do |k|
options[k] = convert_to_hash(options[k]).reverse_merge convert_to_hash(ActionView::Base.swf_default_options[k])
end
options.reverse_merge!(DEFAULTS)
options[:id] ||= source.gsub(/^.*\//, '').gsub(/\.swf$/,'')
options[:div_id] ||= options[:id]+"_div"
options[:width], options[:height] = options[:size].scan(/^(\d*%?)x(\d*%?)$/).first if options[:size]
options[:auto_install] &&= @view.swf_path(options[:auto_install])
options[:flashvars][:id] ||= options[:id]
@mode = options.delete(:mode)
@options = options
unless VALID_MODES.include? @mode
raise ArgumentError, "options[:mode] should be either #{VALID_MODES.join(' or ')}"
end
end
def generate(&block)
if block_given?
@options[:alt] = @view.capture(&block)
if Rails::VERSION::STRING < "2.2"
@view.concat(send(@mode), block.binding)
else
@view.concat(send(@mode))
end
else
send(@mode)
end
end
private
CONCAT = ActiveSupport.const_defined?(:SafeBuffer) ? :safe_concat : :concat
puts CONCAT
def convert_to_hash(s)
case s
when Hash
s
when nil
{}
when String
s.split("&").inject({}) do |h, kvp|
key, value = kvp.split("=")
h[key.to_sym] = CGI::unescape(value)
h
end
else
raise ArgumentError, "#{s} should be a Hash, a String or nil"
end
end
def convert_to_string(h)
h.map do |key_value|
key_value.map{|val| CGI::escape(val.to_s)}.join("=")
end.join("&")
end
def static
param_list = @options[:parameters].map{|k,v| %(<param name="#{k}" value="#{v}"/>) }.join("\n")
param_list += %(\n<param name="flashvars" value="#{convert_to_string(@options[:flashvars])}"/>) unless @options[:flashvars].empty?
html_options = @options[:html_options].map{|k,v| %(#{k}="#{v}")}.join(" ")
r = @view.javascript_tag(
%(swfobject.registerObject("#{@options[:id]}_container", "#{@options[:flash_version]}", #{@options[:auto_install].to_json});)
)
r.send CONCAT, <<-"EOS".strip
<div id="#{@options[:div_id]}"><object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="#{@options[:width]}" height="#{@options[:height]}" id="#{@options[:id]}_container" #{html_options}>
<param name="movie" value="#{@source}" />
#{param_list}
<!--[if !IE]>-->
<object type="application/x-shockwave-flash" data="#{@source}" width="#{@options[:width]}" height="#{@options[:height]}" id="#{@options[:id]}">
#{param_list}
<!--<![endif]-->
#{@options[:alt]}
<!--[if !IE]>-->
</object>
<!--<![endif]-->
</object></div>
EOS
r << @view.javascript_tag(extend_js) if @options[:javascript_class]
r.send CONCAT, library_check
r
end
def dynamic
@options[:html_options] = @options[:html_options].merge(:id => @options[:id])
@options[:parameters] = @options[:parameters].dup # don't modify the original parameters
args = (([@source] + @options.values_at(:div_id,:width,:height,:flash_version)).map(&:to_s) +
@options.values_at(:auto_install,:flashvars,:parameters,:html_options)
).map(&:to_json).join(",")
preambule = @options[:switch_off_auto_hide_show] ? "swfobject.switchOffAutoHideShow();" : ""
r = @view.javascript_tag(preambule + "swfobject.embedSWF(#{args})")
r.send CONCAT, <<-"EOS".strip
<div id="#{@options[:div_id]}">
#{@options[:alt]}
</div>
EOS
r << @view.javascript_tag("swfobject.addDomLoadEvent(function(){#{extend_js}})") if @options[:javascript_class]
r.send CONCAT, library_check
r
end
def extend_js
arglist = case
when @options[:initialize].instance_of?(Array)
@options[:initialize].map(&:to_json).join(",")
when @options.has_key?(:initialize)
@options[:initialize].to_json
else
""
end
"Object.extend($('#{@options[:id]}'), #{@options[:javascript_class]}.prototype).initialize(#{arglist})"
end
def library_check
return "" unless 'development' == ENV['RAILS_ENV']
@view.javascript_tag(<<-"EOS")
if (typeof swfobject == 'undefined') {
document.getElementById('#{@options[:div_id]}').innerHTML = '<strong>Warning:</strong> SWFObject.js was not loaded properly. Make sure you <tt>&lt;%= javascript_include_tag :defaults %&gt;</tt> or <tt>&lt;%= javascript_include_tag :swfobject %&gt;</tt>';
}
EOS
end
end #class Generator
end
end
end

42
vendor/plugins/swf_fu/test/results.rb vendored Normal file
View file

@ -0,0 +1,42 @@
DYNAMIC_RESULT = <<'EOS'
<script type="text/javascript">
//<![CDATA[
swfobject.embedSWF("/swfs/mySwf.swf","mySwf_div","456","123","7","/swfs/expressInstall.swf",{"myVar":"value 1 \u003E 2","id":"mySwf"},{"play":true},{"id":"mySwf"})
//]]>
</script><div id="mySwf_div">
<a href="http://www.adobe.com/go/getflashplayer">
<img src="http://www.adobe.com/images/shared/download_buttons/get_flash_player.gif" alt="Get Adobe Flash player" />
</a>
</div><script type="text/javascript">
//<![CDATA[
swfobject.addDomLoadEvent(function(){Object.extend($('mySwf'), SomeClass.prototype).initialize({"be":"good"})})
//]]>
</script>
EOS
STATIC_RESULT = <<'EOS'
<script type="text/javascript">
//<![CDATA[
swfobject.registerObject("mySwf_container", "7", "/swfs/expressInstall.swf");
//]]>
</script><div id="mySwf_div"><object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="456" height="123" id="mySwf_container" class="lots">
<param name="movie" value="/swfs/mySwf.swf" />
<param name="play" value="true"/>
<param name="flashvars" value="myVar=value+1+%3E+2&id=mySwf"/>
<!--[if !IE]>-->
<object type="application/x-shockwave-flash" data="/swfs/mySwf.swf" width="456" height="123" id="mySwf">
<param name="play" value="true"/>
<param name="flashvars" value="myVar=value+1+%3E+2&id=mySwf"/>
<!--<![endif]-->
<a href="http://www.adobe.com/go/getflashplayer">
<img src="http://www.adobe.com/images/shared/download_buttons/get_flash_player.gif" alt="Get Adobe Flash player" />
</a>
<!--[if !IE]>-->
</object>
<!--<![endif]-->
</object></div><script type="text/javascript">
//<![CDATA[
Object.extend($('mySwf'), SomeClass.prototype).initialize({"be":"good"})
//]]>
</script>
EOS

View file

@ -0,0 +1,152 @@
require File.expand_path(File.dirname(__FILE__)+'/test_helper')
require File.expand_path(File.dirname(__FILE__)+'/results')
class SwfFuTest < ActionView::TestCase
def assert_same_stripped(expect, test)
expect, test = [expect, test].map{|s| s.split("\n").map(&:strip)}
same = expect & test
delta_expect, delta_test = [expect, test].map{|a| a-same}
STDOUT << "\n\n---- Actual result: ----\n" << test.join("\n") << "\n---------\n" unless delta_expect == delta_test
assert_equal delta_expect, delta_test
end
context "swf_path" do
context "with no special asset host" do
should "deduce the extension" do
assert_equal swf_path("example.swf"), swf_path("example")
assert_starts_with "/swfs/example.swf", swf_path("example.swf")
end
should "accept relative paths" do
assert_starts_with "/swfs/whatever/example.swf", swf_path("whatever/example.swf")
end
should "leave full paths alone" do
["/full/path.swf", "http://www.example.com/whatever.swf"].each do |p|
assert_starts_with p, swf_path(p)
end
end
end
context "with custom asset host" do
HOST = "http://assets.example.com"
setup do
ActionController::Base.asset_host = HOST
end
teardown do
ActionController::Base.asset_host = nil
end
should "take it into account" do
assert_equal "#{HOST}/swfs/whatever.swf", swf_path("whatever")
end
end
end
context "swf_tag" do
COMPLEX_OPTIONS = { :width => "456", :height => 123,
:flashvars => {:myVar => "value 1 > 2"}.freeze,
:javascript_class => "SomeClass",
:initialize => {:be => "good"}.freeze,
:parameters => {:play => true}.freeze
}.freeze
should "understand size" do
assert_equal swf_tag("hello", :size => "123x456"),
swf_tag("hello", :width => 123, :height => "456")
end
should "only accept valid modes" do
assert_raise(ArgumentError) { swf_tag("xyz", :mode => :xyz) }
end
context "with custom defaults" do
setup do
test = {:flashvars=> {:xyz => "abc", :hello => "world"}.freeze, :mode => :static, :size => "400x300"}.freeze
@expect = swf_tag("test", test)
@expect_with_hello = swf_tag("test", :flashvars => {:xyz => "abc", :hello => "my friend"}, :mode => :static, :size => "400x300")
ActionView::Base.swf_default_options = test
end
should "respect them" do
assert_equal @expect, swf_tag("test")
end
should "merge suboptions" do
assert_equal @expect_with_hello, swf_tag("test", :flashvars => {:hello => "my friend"}.freeze)
end
teardown { ActionView::Base.swf_default_options = {} }
end
context "with proc options" do
should "call them" do
expect = swf_tag("test", :id => "generated_id_for_test")
assert_equal expect, swf_tag("test", :id => Proc.new{|arg| "generated_id_for_#{arg}"})
end
should "call global default's everytime" do
expect1 = swf_tag("test", :id => "call_number_1")
expect2 = swf_tag("test", :id => "call_number_2")
cnt = 0
ActionView::Base.swf_default_options = { :id => Proc.new{ "call_number_#{cnt+=1}" }}
assert_equal expect1, swf_tag("test")
assert_equal expect2, swf_tag("test")
end
end
context "with static mode" do
setup { ActionView::Base.swf_default_options = {:mode => :static} }
should "deal with string flashvars" do
assert_equal swf_tag("hello", :flashvars => "xyz=abc", :mode => :static),
swf_tag("hello", :flashvars => {:xyz => "abc"}, :mode => :static)
end
should "produce the expected code" do
assert_same_stripped STATIC_RESULT, swf_tag("mySwf", COMPLEX_OPTIONS.merge(:html_options => {:class => "lots"}.freeze).freeze)
end
teardown { ActionView::Base.swf_default_options = {} }
end
context "with dynamic mode" do
should "produce the expected code" do
assert_same_stripped DYNAMIC_RESULT, swf_tag("mySwf", COMPLEX_OPTIONS)
end
end
should "treat initialize arrays as list of parameters" do
assert_match 'initialize("hello","world")', swf_tag("mySwf", :initialize => ["hello", "world"], :javascript_class => "SomeClass")
end
if ActiveSupport.const_defined?(:SafeBuffer)
should "be html safe" do
assert swf_tag("test").html_safe?
end
end
end
context "flashobject_tag" do
should "be the same as swf_tag with different defaults" do
assert_same_stripped swf_tag("mySwf",
:auto_install => nil,
:parameters => {:scale => "noscale", :bgcolor => "#ffffff"},
:flashvars => {:lzproxied => false},
:id => "myFlash"
), flashobject_tag("mySwf", :flash_id => "myFlash")
end
should "be the same with custom settings" do
assert_same_stripped swf_tag("mySwf",
:auto_install => nil,
:parameters => {:scale => "noborder", :bgcolor => "#ffffff"},
:flashvars => {:answer_is => 42},
:id => "myFlash"
), flashobject_tag("mySwf", :flash_id => "myFlash", :parameters => {:scale => "noborder"}, :variables => {:answer_is => 42})
end
end
end

View file

@ -0,0 +1,20 @@
require 'test/unit'
require 'rubygems'
gem 'activesupport', '~> 2.3'
require 'active_support'
gem 'activerecord', '~> 2.3'
require 'active_record'
gem 'actionpack', '~> 2.3'
require 'active_support'
require 'action_view'
require 'action_controller'
#require File.dirname(__FILE__)+'/../../../../config/environment.rb'
require 'action_view/test_case'
require "action_controller/test_process"
require 'shoulda'
require File.dirname(__FILE__) + '/../init'
def assert_starts_with(start, what)
assert what.starts_with?(start), "#{what} does not start with #{start}"
end

6
vendor/plugins/swf_fu/uninstall.rb vendored Normal file
View file

@ -0,0 +1,6 @@
require "fileutils"
dest = File.dirname(__FILE__) + "/../../../public"
FileUtils.rm "#{dest}/javascripts/swfobject.js" rescue puts "Warning: swfobject.js could not be deleted"
FileUtils.rm "#{dest}/swfs/expressInstall.swf" rescue puts "Warning: expressInstall.swf could not be deleted"
Dir.rmdir "#{dest}/swfs/" rescue "don't worry if directory is not empty"