Skip to content

Commit

Permalink
Added JavascriptVariable to wrap a javascript variable in ruby
Browse files Browse the repository at this point in the history
  • Loading branch information
Guilio Karadanais committed May 27, 2009
1 parent 79f6684 commit c605a74
Show file tree
Hide file tree
Showing 2 changed files with 81 additions and 0 deletions.
31 changes: 31 additions & 0 deletions lib/eschaton/javascript/javascript_variable.rb
@@ -0,0 +1,31 @@
module Eschaton

# Encapsulates a javascript variable in a Ruby variable. This can be used to work with a javascript variable within Ruby.
#
# ==== Examples
# # Create a new variable
# my_array = JavascriptVariable.new(:name => :my_array, :value => "new Array()")
# my_array.push("One")
# my_array.push(2)
# my_array.push("Three")
#
# my_array.splice(1, 0, "A new item at position 1")
#
# # Reference an existing variable
# my_existing_array = JavascriptVariable.existing(:var => :my_array)
# my_existing_array.push("Four")
# my_existing_array.push(5)
class JavascriptVariable < JavascriptObject

def initialize(options = {})
options.default! :value => nil, :var => options[:name]

super

if self.create_var?
self << "var #{self.var} = #{options[:value]};"
end
end
end

end
50 changes: 50 additions & 0 deletions test/javascript_variable_test.rb
@@ -0,0 +1,50 @@
require File.dirname(__FILE__) + '/test_helper'

Test::Unit::TestCase.output_fixture_base = File.dirname(__FILE__)

class JavascriptVariableTest < Test::Unit::TestCase

def test_new_variable
Eschaton.with_global_script do |script|
assert_output_fixture 'var points = new Array();
points.push("One");
points.push("Two");',
script.record_for_test {
points = Eschaton::JavascriptVariable.new(:name => :points, :value => "new Array()")
points.push("One")
points.push("Two")
}
end
end

def test_existing_variable
Eschaton.with_global_script do |script|
assert_output_fixture 'points.push("One");
points.push("Two");',
script.record_for_test {
points = Eschaton::JavascriptVariable.existing(:name => :points)
points.push("One")
points.push("Two")
}
end
end

def test_method_translation
Eschaton.with_global_script do |script|
assert_output_fixture 'var points = new Array();
points.push("One");
points.push("Two");
points.translateToCamelCase();
points.withTwoArguments("One", 2);',
script.record_for_test {
points = Eschaton::JavascriptVariable.new(:name => :points, :value => "new Array()")

points.push("One")
points.push("Two")
points.translate_to_camel_case!
points.with_two_arguments("One", 2)
}
end
end

end

0 comments on commit c605a74

Please sign in to comment.