Permalink
Browse files

Added JavascriptVariable to wrap a javascript variable in ruby

  • Loading branch information...
1 parent 79f6684 commit c605a74f10f6f5e74963de562134e6ba7371a8c6 @yawningman yawningman committed May 27, 2009
Showing with 81 additions and 0 deletions.
  1. +31 −0 lib/eschaton/javascript/javascript_variable.rb
  2. +50 −0 test/javascript_variable_test.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
@@ -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.