<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
 
 <title></title>
 <link href="/atom.xml" rel="self"/>
 <link href=""/>
 <updated>2012-01-15T23:33:28-08:00</updated>
 <id></id>

 

 
 <entry>
   <title>Implementing a Jenkins Extension Point with the Native Java API inside a Ruby Plugin</title>
   <link href="/2012/01/16/implementing-a-jenkins-extension-point-with-native-api-in-ruby/"/>
   <updated>Liquid error: undefined method `xmlschema' for "Mon Jan 16 08:00:00 -0500 2012":String</updated>
   <id>/2012/01/16/implementing-a-jenkins-extension-point-with-native-api-in-ruby</id>
   <content type="html">&lt;blockquote&gt;
&lt;p&gt;In which I elaborate why the idomatic Ruby API is sometimes not enough, and describe a method to harness the full power of the underlying Jenkins API while still happily coding your extension in Ruby&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2 id='the_ruby_api'&gt;The Ruby API&lt;/h2&gt;

&lt;p&gt;One of the primary goals of the &lt;a href='http://blog.thefrontside.net/2011/05/12/what-it-take-to-bring-ruby-to-jenkins'&gt;effort to bring Ruby to Jenkins&lt;/a&gt; is to enable developers to extend Jenkins in a way that looks and feels like a normal Ruby environment. This means using rake, bundler ERB, and plain old Ruby objects to roll your plugin.&lt;/p&gt;

&lt;p&gt;For example, the &lt;a href='https://github.com/jenkinsci/jenkins/blob/master/core/src/main/java/hudson/tasks/BuildStep.java'&gt;native BuildStep&lt;/a&gt; class is made available through the &lt;a href='https://github.com/jenkinsci/jenkins-plugin-runtime.rb/blob/master/lib/jenkins/tasks/build_step.rb'&gt;Ruby BuildStep&lt;/a&gt;. They are similar to be sure, but the Ruby object is much less complicated, and actually bears no relation to its Java equivalent inside the Java hiearchy of inheritance.&lt;/p&gt;

&lt;p&gt;Exposing this simplicity is a worthy goal, but to do so requires careful consideration of each Jenkins Java API and how to provide its functionality in the Ruby way &amp;#8211;no mean feat given the breadth of the Jenkins.&lt;/p&gt;

&lt;p&gt;Sadly, it means that these Ruby-friendly APIs must necessarily lag behind their Java counterparts.&lt;/p&gt;

&lt;p&gt;This can be a serious source of frustration for those looking to dive into Jenkins Ruby development right now. Initial excitement is quickly dulled when you find out that the extension point that you wanted to implement is unavailable from Ruby land. You might get discouraged and feel like you might as well be coding your plugin with Java.&lt;/p&gt;

&lt;p&gt;Well don&amp;#8217;t lose heart! I&amp;#8217;d like to share with you a super easy way to write your extension points in Ruby even when there isn&amp;#8217;t a friendly wrapper. We&amp;#8217;ll actually implement a very handy extension point called &lt;code&gt;RunListener&lt;/code&gt; within a Ruby plugin even though it is not part of the official Ruby API. We&amp;#8217;ll do it by scripting the Java class directly with JRuby&amp;#8217;s Java integration feature, and then register it directly with the plugin runtime.&lt;/p&gt;

&lt;h2 id='the_extension_point'&gt;The Extension Point&lt;/h2&gt;

&lt;p&gt;We&amp;#8217;ll be working with the Jenkins &lt;a href='https://github.com/jenkinsci/jenkins/blob/master/core/src/main/java/hudson/model/listeners/RunListener.java'&gt;RunListener&lt;/a&gt; interface. This is a wonderful extension point that allows you to receive callbacks at each point during the actual running of a build. There&amp;#8217;s currently no nice ruby API for it, but we won&amp;#8217;t let that stop us.&lt;/p&gt;

&lt;p&gt;First, let&amp;#8217;s create a new plugin called &lt;em&gt;my-listener&lt;/em&gt;. We&amp;#8217;ll do this with the &lt;code&gt;jpi new&lt;/code&gt; command.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;legolas:Jenkins cowboyd$ jpi new my-listener
    create  my-listener/Gemfile
    create  my-listener/my-listener.pluginspec&lt;/code&gt;&lt;/pre&gt;

&lt;blockquote&gt;
&lt;p&gt;Fun fact: &amp;#8216;jpi&amp;#8217; is an acronym for (J)enkins (P)lug-(I)n. You can install the tool with rubygems: &lt;code&gt;gem install jpi&lt;/code&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Next, we&amp;#8217;ll cd into our new plugin and create our listener class inside the models/ directory. Jenkins will automatically evaluate everything in this directory on plugin initialization.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;legolas:Jenkins cowboyd$ cd my-listener/
legolas:my-listener cowboyd$ mkdir models
legolas:my-listener cowboyd$ touch models/my_listener.rb&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Our ultimate goal here is to implement a &lt;code&gt;RunListener&lt;/code&gt;, so let&amp;#8217;s go ahead and start our class definition inside that file.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;class MyListener &amp;lt; Java.hudson.model.listeners.RunListener
  def initialize()
    super(Java.hudson.model.Run.java_class)
  end
end&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;There&amp;#8217;s a couple key takeaways here. First, notice that we use JRuby integration to extend the class &lt;code&gt;hudson.model.listeners.RunListener&lt;/code&gt; directly. Second, and this is a gotcha anytime you extend a Java class: you &lt;em&gt;must&lt;/em&gt; invoke one of the Java super constructors if it does not have a default constructor. I can&amp;#8217;t tell you how many times I&amp;#8217;ve been bitten by this.&lt;/p&gt;

&lt;p&gt;In our case, the &lt;code&gt;RunListener&lt;/code&gt; class filters which jobs it will provide callbacks for by class. By providing a more specific class to the constructor, you limit the scope of jobs you&amp;#8217;ll receive to subclasses of that class. For our purposes, we cast a pretty wide net by selecting all builds via the &lt;code&gt;AbstractBuild&lt;/code&gt; Java class.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Pro Tip: when you&amp;#8217;re implementing a native Java API, it really helps to have the javadoc open in one window so that you can view the documentation and crib from the source&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Now that we&amp;#8217;ve got our class defined, let&amp;#8217;s implement some methods! We&amp;#8217;ll add callbacks for when a build is started and when it&amp;#8217;s completed.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;class MyListener &amp;lt; Java.hudson.model.listeners.RunListener
  def initialize()
    super(Java.hudson.model.AbstractBuild.java_class)
  end
  def onStarted(run, listener)
    listener.getLogger().println(&amp;quot;onStarted(#{run})&amp;quot;)
  end
  def onCompleted(run, listener)
    listener.getLogger().println(&amp;quot;onCompleted(#{run})&amp;quot;)
  end
end
Jenkins.plugin.register_extension MyListener.new&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;And finally, on the last line, we actually inform Jenkins about the existence of our new Listener with the call to &lt;code&gt;Jenkins.plugin.register_extension&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;And that&amp;#8217;s about it. We can start up our test server with our &lt;code&gt;jpi&lt;/code&gt; tool to see our listener in action.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;legolas:my-listener cowboyd$ jpi server
Listening for transport dt_socket at address: 8000
Running from: /Users/cowboyd/.rvm/gems/jruby-1.6.5/gems/jenkins-war-1.446/lib/jenkins/jenkins.war
...
Jan 16, 2012 12:46:15 AM ruby.RubyRuntimePlugin start
INFO: Injecting JRuby into XStream
Loading /Users/cowboyd/Projects/Jenkins/my-listener/models/my_listener.rb
INFO: Prepared all plugins
...
INFO: Jenkins is fully up and running&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;To view the output, create a freestyle build called HelloWorld that doesn&amp;#8217;t have any build steps at all, build it and view the console output. You should see something like this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;Started by user anonymous
onStarted(#&amp;lt;Java::HudsonModel::FreeStyleBuild:0x2870068a&amp;gt;)
onCompleted(#&amp;lt;Java::HudsonModel::FreeStyleBuild:0x2870068a&amp;gt;)
Finished: SUCCESS&lt;/code&gt;&lt;/pre&gt;

&lt;h2 id='the_sweet_reality'&gt;The Sweet Reality&lt;/h2&gt;

&lt;p&gt;Even though we were dealing more directly with Java, we were still able to use all of the simplicity that comes with developing plugins in Ruby. Furthermore, even though our extension point was just scripted Java, it doesn&amp;#8217;t mean that inside its methods it can&amp;#8217;t call as much pure Ruby code as its heart desires.&lt;/p&gt;

&lt;p&gt;I hope that if you&amp;#8217;re considering writing your next (or your first!) Jenkins plugin in Ruby, you&amp;#8217;ll feel confident that you can always fall back to the native APIs at any point.&lt;/p&gt;</content>



 </entry>
 
 <entry>
   <title>Ruby for Jenkins Goes Pre-Alpha</title>
   <link href="/2011/09/13/ruby-for-jenkins-goes-pre-alpha/"/>
   <updated>2011-09-13T00:00:00-07:00</updated>
   <id>/2011/09/13/ruby-for-jenkins-goes-pre-alpha</id>
   <content type="html">&lt;p&gt;To quote Dave Bowman, &amp;#8220;something wonderful happened&amp;#8221; last week during the weekly &lt;a href='http://wiki.jenkins-ci.org/display/JENKINS/Jenkins+plugin+development+in+Ruby' title='Jenkins Ruby Hacking'&gt;Jenkins-Ruby hack session&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;We were able to boot a &lt;a href='https://github.com/cowboyd/jenkins-prototype-ruby-plugin' title='Prototype Ruby Plugin'&gt;plugin written in pure Ruby&lt;/a&gt; into a Jenkins server just by executing a single command from the command line (rake server). Furthermore, this command did not involve a compilation step, and the plugin that it booted did not bare a trace of evidence that it was to be loaded into a server written in Java.&lt;/p&gt;

&lt;p&gt;That&amp;#8217;s right. Using nothing but good &amp;#8216;ol Bundler and Rake, we hoisted a pure Ruby plugin into the Jenkins runtime. And I can tell you that after hacking on this for almost a year: it felt&amp;#8230; so&amp;#8230;. good&amp;#8230;. man.&lt;/p&gt;

&lt;p&gt;It&amp;#8217;s not time to declare victory yet, but at least the first two of &lt;a href='/2011/05/12/what-it-take-to-bring-ruby-to-jenkins' title='What it takes to bring Ruby to Jenkins'&gt;our major goals&lt;/a&gt; have been realized, and that is definitely a cause to celebrate.&lt;/p&gt;

&lt;p&gt;Practically, this means that rubyists can check out the source and get hacking without needing any knowledge of Java or any Java toolchain. That&amp;#8217;s why I think it&amp;#8217;s safe to officially declare the project to be in a &lt;strong&gt;&lt;em&gt;pre-alpha&lt;/em&gt;&lt;/strong&gt; state.&lt;/p&gt;

&lt;p&gt;It isn&amp;#8217;t yet for the faint of heart, and you&amp;#8217;re sure to find many things confusing and difficult. But at least those who know only Ruby can contribute bug reports, identify pain points, and contribute to the creative process.&lt;/p&gt;

&lt;p&gt;It&amp;#8217;s 8:20am, but it still feels like Miller time.&lt;/p&gt;</content>



 </entry>
 
 <entry>
   <title>The Ruby Racer isn't threadsafe... yet.</title>
   <link href="/2011/06/13/therubyracer-isnt-threadsafe-yet/"/>
   <updated>Liquid error: undefined method `xmlschema' for "13 June 2011":String</updated>
   <id>/2011/06/13/therubyracer-isnt-threadsafe-yet</id>
   <content type="html">&lt;blockquote&gt;&lt;strike&gt;In which I explain problems unique to running The Ruby Racer in a multithreaded environment, 
which users are affected by these problems, and what is to be done for them.&lt;/strike&gt;
&lt;p&gt;UPDATE: This issue has been resolved with &lt;a href='http://rubygems.org/gems/therubyracer/versions/0.9.1'&gt;version 0.9.1&lt;/a&gt;. You should be able to stop reading here, update your Gemfile, and have a great day. That said, please don&amp;#8217;t let me discourage you from continuing down the page. It&amp;#8217;s riveting.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;There have been a number of crashes reported in &lt;a href='https://github.com/cowboyd/therubyracer/issues/79'&gt;several&lt;/a&gt; &lt;a href='https://github.com/rails/rails/issues/1667'&gt;different&lt;/a&gt; &lt;a href='http://redmine.ruby-lang.org/issues/4821'&gt;places&lt;/a&gt; for which &lt;a href='http://github.com/cowboyd/therubyracer'&gt;The Ruby Racer&lt;/a&gt; is the culprit. For the most part, these are people running an Rails 3.1 application in a multithreaded webserver such as WEBrick, but as we&amp;#8217;ll see, it could be anybody that is using The Ruby Racer in a mulithreaded environment. In order to speak to these and future issues in one place, as well as prevent the spread of any misinformation or impressions, I wanted to very quickly explain what exactly is causing these crashes, who is affected by them and where, and finally how we&amp;#8217;re going to make them go away.&lt;/p&gt;

&lt;h2 id='background'&gt;Background&lt;/h2&gt;

&lt;p&gt;When an instance of V8 starts running, it associates all of its global state with the currently running native OS thread. By global state, I mean things like heap storage, stacks, callbacks&amp;#8230; everything that it needs to make JavaScript happen. Every time you &lt;code&gt;eval()&lt;/code&gt; a script or you allocate an object with &lt;code&gt;new&lt;/code&gt;, it retrieves that state from the executing thread to perform that operation.&lt;/p&gt;

&lt;p&gt;In a single threaded application, that&amp;#8217;s the end of the story. This is because every V8 operation happens from the same thread as the rest of your code, so the V8 state is always right there ready at all times. If you&amp;#8217;re running your app in a rack server like Passenger or Unicorn that uses a multi-process model to achieve concurrency, you&amp;#8217;ll never see this crash because you don&amp;#8217;t use threads. Also, if you&amp;#8217;re running on MRI 1.8.7 which uses green threads, you will also not be affected. While you may have more than one Ruby thread in your application, you still only have one &lt;em&gt;native&lt;/em&gt; OS thread which is what V8 will use.&lt;/p&gt;

&lt;p&gt;The problem comes in when you are using Ruby 1.9 in a multi-threaded environment and you access V8 from more than one thread. This is because 1.9 uses native OS threads under the covers for its own threading API. When The Ruby Racer starts up V8, it uses whatever thread happens to be running as the home for its runtime data. Then, when you try and do some JavaScript operation from another thread, V8 can&amp;#8217;t find its state, freaks out and crashes your entire process.&lt;/p&gt;

&lt;p&gt;Luckily, V8 does give us some help here. It provides a &lt;a href='http://bespin.cz/~ondras/html/classv8_1_1Unlocker.html'&gt;locker API&lt;/a&gt; as a way to deal with threading issues. It acts as both mutex on a V8 instance while at the same time providing a facility to access it from different threads. We can wrap calls that touch V8 with a &lt;code&gt;Locker&lt;/code&gt; in order to prevent these crashes. e.g.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;V8::C::Locker() do
  #... code that calls V8
end&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;That sounds simple enough: just never access V8 without a lock and you&amp;#8217;re good. In fact, &lt;a href='https://github.com/sstephenson/execjs/blob/b67a563ab4c6e26dc468e948d523456d531463f9/lib/execjs/ruby_racer_runtime.rb#L70-86'&gt;ExecJS does this&lt;/a&gt; whenever it invokes its therubyracer runtime, and it works&amp;#8230; almost.&lt;/p&gt;

&lt;h2 id='i_would_have_gotten_away_with_it_too_if_it_hadnt_been_for_you_pesky_gcs'&gt;I would have gotten away with it too if it hadn&amp;#8217;t been for you pesky GCs&lt;/h2&gt;

&lt;p&gt;If ExecJS locks V8, then why am I still crashing, and at seemingly random intervals?&lt;/p&gt;

&lt;p&gt;The problem comes when we need to run garbage collection. The awesome thing about The Ruby Racer is that it lets you hold on to V8 objects from Ruby. It does this by using a proxy &amp;#8211;a ruby object that implements all its behavior by delegating to an underlying JavaScript object. As long as Ruby holds a reference to that proxy, the proxy will in turn hold a reference to its underlying V8 object. However, when Ruby no longer holds a reference to the proxy and the proxy is garbage collected, we need to tell V8 that we aren&amp;#8217;t holding a reference to the underlying object anymore. And, as you may have guessed, in order to remove references to V8 objects, you need to hold what? Yep, the V8 lock. To operate properly, GC also needs to lock V8. Sadly, it does not, which explains why crashes continue to happen at random places.&lt;/p&gt;

&lt;p&gt;You might be asking yourself, &amp;#8220;why not just lock V8 in your GC routines and have done with it?&amp;#8221; The answer is that it would be a terribly dangerous and irresponsible thing to do.&lt;/p&gt;

&lt;p&gt;Suppose that thread &lt;code&gt;A&lt;/code&gt; has V8 locked and is doing some fancy JavaScript stuff. At some point, we do a context switch over to thread &lt;code&gt;B&lt;/code&gt; which is not doing anything even remotely JavaScriptful like loading ActiveRecords from the database or something. Thread &lt;code&gt;B&lt;/code&gt; is chugging threw lots of memory, and all of a sudden triggers GC. There are some V8 objects that need cleanup due to our JavaScript activities over in thread &lt;code&gt;A&lt;/code&gt;, so it tries to lock V8, but uh-oh, thread &lt;code&gt;A&lt;/code&gt; already holds the V8 lock, so GC may have to wait forever until it becomes available. Deadlock!&lt;/p&gt;

&lt;p&gt;The answer is that instead of immediately releasing v8 objects inside the GC thread, we need to equeue them somewhere where they can be released. This probably means starting a thread per V8 instance to consume this reference queue and release them in the context of a V8 lock that isn&amp;#8217;t contending for any other resources. While the answer is not trivial, I don&amp;#8217;t expect it to be that complex.&lt;/p&gt;

&lt;h2 id='what_to_do_what_to_do'&gt;What to do? What to do?&lt;/h2&gt;

&lt;p&gt;In the mean time, there is a &lt;a href='https://gist.github.com/1011718'&gt;workaround&lt;/a&gt; for locking V8 with each request, which will ensure that GC running in that request will have already acquired the V8 lock. Bear in mind that this is not a silver bullet, and you still could encounter crashes and deadlocks, but they should be very few and far between. If, as is the case with most people, you are just using a multithreaded server in your development environment but deploy to multi-process model, then this should be sufficient. If on the other hand you run multi-threaded in production, then you should definitely &lt;em&gt;not&lt;/em&gt; be locking V8 in your middleware since this will effectively synchronize every request. Not a good idea.&lt;/p&gt;

&lt;p&gt;No matter which category you fall into, I expect that we&amp;#8217;ll have a beta fix by the end of this week, and if all goes well, a patch release after another. This may seem like a long time for such a small thing as coordinating locking with GC, but my experience tells me that threading is not a thing best done by humans, and so there will inevitable stumbles and cursing.&lt;/p&gt;

&lt;p&gt;Also, I&amp;#8217;m keen to make sure that any solution is both invisible to you the developer, as well as compatible with other Ruby versions and implementations. This deserves some thought.&lt;/p&gt;

&lt;h2 id='what_youre_still_here'&gt;What? you&amp;#8217;re still here?&lt;/h2&gt;

&lt;p&gt;Alright, time to stop talking and get started with the repairs. I just wanted to take a moment to let you know what the problem was, why it was happening, how&amp;#8217;re you&amp;#8217;re affected, what you can do now, and when you can expect a more permanent fix.&lt;/p&gt;</content>



 </entry>
 
 <entry>
   <title>What it takes to bring Ruby to Jenkins</title>
   <link href="/2011/05/12/what-it-take-to-bring-ruby-to-jenkins/"/>
   <updated>2011-05-12T00:00:00-07:00</updated>
   <id>/2011/05/12/what-it-take-to-bring-ruby-to-jenkins</id>
   <content type="html">&lt;p&gt;&amp;#8220;Jenkins Ruby Plugins&amp;#8221; are at an important, yet fragile stage of their life. Over the past several months, we have made tremendous progress towards making extending Jenkins with nothing but Ruby a blissful reality. However, at this moment, they exist only as a collection of hacks, or, to frame it more kindly, &amp;#8220;proofs of concept&amp;#8221; all buried quite deeply in a &lt;a href='http://github.com/cowboyd/fog.hpi'&gt;terribly named repo on github&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;To name a few of them, we are now able to&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;automatically discover Ruby plugins and register them&lt;/li&gt;

&lt;li&gt;work with Jenkins internals like BuildWrapper, RootActions, etc.. via a native Ruby-like API&lt;/li&gt;

&lt;li&gt;persist mixed hierarchies of Java and Ruby objects transparently as Jenkins configuration&lt;/li&gt;

&lt;li&gt;use ERB to template views, while still having access to the standard UI helpers&lt;/li&gt;

&lt;li&gt;extend the Jenkins REST API from Ruby&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;This is by no means an exhaustive list, but I want to stress just how far we&amp;#8217;ve come before I talk about where it is that we need to go.&lt;/p&gt;

&lt;p&gt;While the work done so far represents some phenomenal accomplishments, in the end, they are only technical accomplishments which do not together create a coherent developer experience. So now, for this endeavor to succeed, we must focus our attention on making that &lt;em&gt;entire experience&lt;/em&gt;, from project start to release after release, as frictionless as possible.&lt;/p&gt;

&lt;p&gt;To that end, I propose the following high level goal for the Jenkins Ruby Plugins project:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;To provide the facility to create, develop and release extensions for Jenkins with nothing but knowledge of the language, tools and best practices of the Ruby community.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;This is, I think, the most important ideal to aspire to when claiming to provide a Ruby development experience. Unless it feels like the real McCoy, then you aren&amp;#8217;t really developing Ruby at all, you&amp;#8217;re just scripting Java with JRuby. You won&amp;#8217;t fool anybody, and there will be far less enthusiasm and adoption.&lt;/p&gt;

&lt;p&gt;That said, several things follow logically from this thesis, the first of which is:&lt;/p&gt;

&lt;h3 id='absolutely_positively_no_maven'&gt;Absolutely, Positively, No Maven!&lt;/h3&gt;

&lt;p&gt;This is not an ideological stance on the value of Maven as a &lt;strike&gt;wretched pile of toad sick&lt;/strike&gt; software development tool. Rather, it is an explicit acknowledgement that it is not a Ruby tool, it doesn&amp;#8217;t fit with the community&amp;#8217;s style, and if you&amp;#8217;re using it you might not be doing Java, but you &lt;em&gt;certainly&lt;/em&gt; aren&amp;#8217;t doing Ruby. Instead, we should turn to the Ruby tools that occupy this same space: Rake for scripting the build, and Bundler for dependency management.&lt;/p&gt;

&lt;h3 id='rubylike_project_structure'&gt;Ruby-Like Project Structure&lt;/h3&gt;

&lt;p&gt;If we aren&amp;#8217;t going to use Maven, then why should we be constrained by the project directory structure that it imposes. &lt;code&gt;src/main/resources/what?&lt;/code&gt; Nope. Just one glance at Jenkins Ruby Plugin&amp;#8217;s layout in an editor or file system browser should put a Rubyist&amp;#8217;s mind right at ease. You see that? There&amp;#8217;s your &lt;code&gt;Gemfile&lt;/code&gt; just where you left him. And oh, your pals &lt;code&gt;lib/&lt;/code&gt; and &lt;code&gt;spec/&lt;/code&gt; are there too. Let&amp;#8217;s get right to work!&lt;/p&gt;

&lt;h3 id='managing_the_project_lifecycle'&gt;Managing The Project Life-Cycle&lt;/h3&gt;

&lt;p&gt;From inception to release, you should be able to manage all aspects of your Jenkins plugin with Ruby. There must be single commands (or rake tasks) to&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;conjure a new plugin into existence&lt;/li&gt;

&lt;li&gt;generate model/view boilerplate&lt;/li&gt;

&lt;li&gt;run a server with the plugin loaded&lt;/li&gt;

&lt;li&gt;package, push, tag and release a plugin to update-center&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id='testing'&gt;Testing&lt;/h3&gt;

&lt;p&gt;The importance of testing in the Ruby community cannot be overstated. The Ruby Tools need to provide a clear path to testing the plugin at both the unit and functional levels.&lt;/p&gt;

&lt;h3 id='documentation'&gt;Documentation&lt;/h3&gt;

&lt;p&gt;The &amp;#8220;Ruby-like&amp;#8221; API that plugin development provides is similar, but not equivalent to its native Java equivalent. It is critical that this API be well documented, so that developers can understand it, and do not find themselves constantly referring to the JavaDoc, which they may very well not understand (it being Java), and might be misleading given the natural asymmetries of the two APIs.&lt;/p&gt;

&lt;h2 id='heed_the_call'&gt;Heed the Call!&lt;/h2&gt;

&lt;p&gt;There are plenty of people who would love to see this project get done, but don&amp;#8217;t know where to start. I know this because I was one of them. The upshot is that now, as I&amp;#8217;ve just described, there is plenty of work to be done that doesn&amp;#8217;t require any knowledge of Java and very little knowledge of Jenkins internals. That means that &lt;em&gt;you&lt;/em&gt; can contribute in a meaningful way!&lt;/p&gt;

&lt;p&gt;Next week, I&amp;#8217;ll be publishing some specifications in the form of Cucumber scenarios for some of the features up above that we can discuss and then hopefully start implementing.&lt;/p&gt;

&lt;p&gt;But the most important thing that you can do is to join in on the conversation!&lt;/p&gt;

&lt;p&gt;&lt;a href='irc://freenode.net/jenkins'&gt;irc&lt;/a&gt;, and &lt;a href='http://groups.google.com/group/jenkinsrb'&gt;email&lt;/a&gt; are just a few of the ways to reach out!&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Update. I have posted the first scenario: &lt;a href='https://github.com/cowboyd/jenkins.rb/blob/ruby-plugin-development/features/plugins/create-new-plugin.feature'&gt;creating a plugin&lt;/a&gt;. The first bounty is officially posted.&lt;/p&gt;
&lt;/blockquote&gt;</content>



 </entry>
 
 <entry>
   <title>Wrapping each Hudson distribution in its own RubyGem</title>
   <link href="/2011/01/06/wrapping-each-hudson-distribution-in-its-own-rubygem/"/>
   <updated>Liquid error: undefined method `xmlschema' for "06 Jan 2011":String</updated>
   <id>/2011/01/06/wrapping-each-hudson-distribution-in-its-own-rubygem</id>
   <content type="html">&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;&lt;em&gt;Update&lt;/em&gt;&lt;/strong&gt;: As of version &lt;code&gt;1.396&lt;/code&gt;, this is applicable to the &lt;a href='http://jenkins-ci.org'&gt;Jenkins&lt;/a&gt; project. &lt;code&gt;1.395&lt;/code&gt; will be the last version of the hudson-war gem&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;As you may or may not know, we here at The FrontSide have been working since late last year to create a proper ruby environment for extending hudson. This is no mean feat because it implies not only the ability to use nothing but ruby &lt;em&gt;code&lt;/em&gt; to implement hudson plugins, but just as importantly, the ability to use nothing but ruby &lt;em&gt;tools&lt;/em&gt; to develop them. That means no javac, no &lt;a href='http://en.wikipedia.org/wiki/Jar_file'&gt;jar files&lt;/a&gt;, no &lt;a href='http://en.wikipedia.org/wiki/WAR_%28Sun_file_format%29'&gt;war files&lt;/a&gt;, and for the love of all that is holy: &lt;a href='http://kent.spillner.org/blog/work/2009/11/14/java-build-tools.html'&gt;absolutely, positively, no maven&lt;/a&gt;. In short, the only folks you&amp;#8217;ll need to know to get in the door with Hudson are your pals Ruby, Rake and Bundler.&lt;/p&gt;

&lt;p&gt;Of course, all those jars and wars and perhaps some class generation will be there behind the scenes. After all, we&amp;#8217;ll still need to compile java stubs that depend on core Hudson classes. We&amp;#8217;ll still need to package your plugin along with its ruby code and dependencies in a jar file, and we&amp;#8217;ll still need to take care of all the blah, blah, MANIFEST, blah, META-INF, WEB-INF, blah, blah, blah&amp;#8230;&lt;/p&gt;

&lt;h2 id='the_war'&gt;The War&lt;/h2&gt;

&lt;p&gt;If we&amp;#8217;re going to do the compilation against Hudson core from within ruby and Rake instead of maven, then we&amp;#8217;re going to need a reliable way to get at the core hudson classes so that we can use them in our compilation classpath. Not only that, but as part of the development process, you&amp;#8217;re going to want to test your plugins against a fully functioning hudson server. Luckily, both of these are contained in the full hudson distribution that you download as a single war file. Wouldn&amp;#8217;t it be nice if you had a simple way to get at a specific version of one of those wars and then get at all those java goodies contained therein?&lt;/p&gt;

&lt;h2 id='the_gem'&gt;The Gem&lt;/h2&gt;

&lt;p&gt;To my thinking, this sounds like a job for: RubyGems! That&amp;#8217;s why we&amp;#8217;re introducing the new &lt;a href='https://rubygems.org/gems/hudson-war'&gt;hudson-war&lt;/a&gt; gem, which does nothing except wrap a single hudson distribution so that it can be managed coherently just like any other ruby component. Want the latest warfile?&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;gem install hudson-war&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Or perhaps you need hudson 1.386? That&amp;#8217;s fine, hudson-war versions are the same as the hudson distributions they wrap.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;gem install hudson-war --version 1.386&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;It&amp;#8217;s not just a war file either. In keeping with the best traditions of OOP data comes bundled with behavior. The gem comes with a ruby API and a CLI baked in to help us do all the nifty things we might want to do with a war file. For starters, you might want to know where it is.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;legolas:~ cowboyd$ hudson.war location
/Users/cowboyd/.rvm/gems/ruby-1.8.7-p174/gems/hudson-war-1.386/lib/hudson/hudson.war&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;If you want to unpack it to a particular location then&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;legolas:~ cowboyd$ hudson.war unpack tmp
jar xvf /Users/cowboyd/.rvm/gems/ruby-1.8.7-p174/gems/hudson-war-1.386/lib/hudson/hudson.war -C tmp/&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;You can run a test server with it&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;legolas:~ cowboyd$ hudson.war server --daemon
Forking into background to run as a daemon.
Use --logfile to redirect output to a file
legolas:~ cowboyd$ hudson.war server --kill&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Beyond the basics, let&amp;#8217;s say you want to do something interesting like compile some java code against the hudson core. You&amp;#8217;re gonna need a classpath, and you can get it with:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;legolas:~ cowboyd$ hudson.war classpath
/Users/cowboyd/.hudson/wars/1.386/WEB-INF/lib/hudson-core-1.386.jar&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;You can even compile java code with it directly. Here we compile a trivial class that has a dependency on hudson.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;legolas:~ cowboyd$ cat &amp;gt; ImportsHudson.java 
import hudson.model.Hudson;
public class ImportsHudson {
  public static void main(String args[]) {
    System.out.printf(&amp;quot;The Hudson Model object&amp;#39;s class is %s\n&amp;quot;, Hudson.class.getName());
  }
}
legolas:~ cowboyd$ hudson.war javac ImportsHudson.java
legolas:~ cowboyd$ java -cp .:`hudson.war classpath` ImportsHudson
The Hudson Model object&amp;#39;s class is hudson.model.Hudson&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;It&amp;#8217;s like RVM for hudson. Wrangling java has never been so fun!&lt;/p&gt;

&lt;h2 id='the_war_gemmer'&gt;The War Gemmer&lt;/h2&gt;

&lt;p&gt;Befitting a continuous integration project, the Hudson team releases a new version at least every two weeks, and sometimes even sooner. It can be a bitch to keep up with, so I&amp;#8217;ve set up a &lt;a href='http://github.com/cowboyd/hudson-wargemmer'&gt;wargemmer hudson&lt;/a&gt; task to periodically poll the update center to see if there is a new release. If there is, it&amp;#8217;ll gem it right up and push it to rubygems. No fuss no muss.&lt;/p&gt;

&lt;p&gt;Let the war begin!&lt;/p&gt;</content>



 </entry>
 
 <entry>
   <title>We must come together to honor the command line</title>
   <link href="/2010/11/14/we-must-come-together-to-honor-the-command-line/"/>
   <updated>Liquid error: undefined method `xmlschema' for "14 Nov 2010":String</updated>
   <id>/2010/11/14/we-must-come-together-to-honor-the-command-line</id>
   <content type="html">&lt;p&gt;I reap no joy from writing command line interfaces in Ruby, and about 5 minutes before leaving RubyConf this year I realized that I am not alone.&lt;/p&gt;

&lt;p&gt;It&amp;#8217;s not angst I feel so much as a general &lt;em&gt;&amp;#8220;meh&amp;#8221;&lt;/em&gt;: There&amp;#8217;s a fairly decent out-of-the-box way to do it in &lt;code&gt;OptionParser&lt;/code&gt;, but the minute you want to introduce commands is when the muddling begins. Sure you can see your way through it, but it&amp;#8217;s never robust and you always get smacked in the ass by the edge cases that inevitably come along.&lt;/p&gt;

&lt;h2 id='it_aint_for_lack_of_trying'&gt;It ain&amp;#8217;t for lack of trying&lt;/h2&gt;

&lt;p&gt;My own abortive attempts not withstanding, I&amp;#8217;ve tried in the last year at least 3 different libraries for parsing CLI options in my applications and gems. These are &lt;a href='http://github.com/davetron5000'&gt;gli&lt;/a&gt;, &lt;a href='http://github.com/wycats/thor'&gt;thor&lt;/a&gt; and &lt;a href='http://github.com/joshbuddy/optitron'&gt;optitron&lt;/a&gt;. I have known and loved each of these libraries in its own way, but ultimately all of them left me feeling unsatisfied. I won&amp;#8217;t go into my specific dissatisfactions with each here, but suffice it to say that my malaise was shared. The general consensus of the cohort at the bar was that despite the recent innovations and improvements in the space, we&amp;#8217;d really have just been better off with &amp;#8221;&lt;code&gt;OptionParser&lt;/code&gt; plus commands.&amp;#8221;&lt;/p&gt;

&lt;h2 id='but_we_should_do_better'&gt;But we should do better&lt;/h2&gt;

&lt;p&gt;Better off for sure, but is that still what we want: to just get by?&lt;/p&gt;

&lt;p&gt;No. we need a way to write command lines that feels like judo: deploying minimal force to effortlessly sling mountains of code.&lt;/p&gt;

&lt;p&gt;I say we can have our cake and eat it too. I say our command lines can be easy. I say our command lines can be sexy. I say our command lines can be so awesome that they crap rainbows and have herds of unicorns come thundering out of their asses.&lt;/p&gt;

&lt;p&gt;That&amp;#8217;s why I&amp;#8217;m starting the &lt;a href='http://github.com/cowboyd/optimal'&gt;optimal&lt;/a&gt; project. It may lead to nothing. It might even lead eventually to some code&amp;#8230; that&amp;#8217;s not the point right now though. The point is to reach out to everyone who feels strongly about this and ask them to contribute ideas and requirements in order to build a consensus on the next generation of CLI builder that everybody can be proud of.&lt;/p&gt;

&lt;p&gt;It certainly will not happen overnight, but for the betterment of all, it&amp;#8217;s high time to find the true successor to OptionParser: the one the community sees eventually integrated into the standard library.&lt;/p&gt;</content>



 </entry>
 
 <entry>
   <title>Accessing JavaScript Objects From Ruby</title>
   <link href="/2010/10/25/accessing-javascript-objects-from-ruby/"/>
   <updated>Liquid error: undefined method `xmlschema' for "25 October 2010":String</updated>
   <id>/2010/10/25/accessing-javascript-objects-from-ruby</id>
   <content type="html">&lt;p&gt;Awhile back, I wrote a post on how to &lt;a href='/2010/06/30/accessing-ruby-objects-from-V8/'&gt;access Ruby objects from inside your JavaScript enviroment&lt;/a&gt; when using &lt;a href='http://github.com/cowboyd/therubyracer'&gt;The Ruby Racer&lt;/a&gt;. It showed just some of the many ways that you can access Ruby state and call Ruby code from within JavaScript. However, the story doesn&amp;#8217;t end there. The Ruby Racer is, after all, a two way bridge, and I thought it would be useful to document some of the ways in which you can access your JavaScript environment from within Ruby.&lt;/p&gt;

&lt;p&gt;Let&amp;#8217;s start with the &lt;code&gt;Context#eval&lt;/code&gt; method, which is used to execute JavaScript code from Ruby. Its the most intuitive way, and what gets used most often for examples.&lt;/p&gt;

&lt;p&gt;Given a string, it compiles it as JavaScript source and then executes it inside the context. Nothing crazy there:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;V8::Context.new do |cxt|
  cxt.eval(&amp;#39;1 + 1&amp;#39;) #=&amp;gt; 2
  cxt.eval(&amp;#39;foo = {bar: &amp;quot;bar&amp;quot;, baz: &amp;quot;baz&amp;quot;}&amp;#39;)
  cxt.eval(&amp;#39;foo.bar&amp;#39;) #=&amp;gt; &amp;quot;bar&amp;quot;
  cxt.eval(&amp;#39;foo.baz&amp;#39;) #=&amp;gt; &amp;quot;baz&amp;quot;
  cxt.eval(&amp;#39;new Object()&amp;#39;) #=&amp;gt; [object Object]
end&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Among other things, the context captures what functions and objects are defined in the global scope whenever anything gets &lt;code&gt;eval()&lt;/code&gt;&amp;#8216;d. So, for example, the &lt;code&gt;Object&lt;/code&gt; constructor used in the last line is stored in the context.&lt;/p&gt;

&lt;p&gt;As a tool for embedding however, &lt;code&gt;eval()&lt;/code&gt; is the most blunt and (often) inefficient method available. For this reason &lt;a href='http://github.com/cowboyd/therubyracer'&gt;The Ruby Racer&lt;/a&gt;, sports an extensive Ruby API for interacting with JavaScript objects which includes accessing properties, calling functions and methods, as well as creating new instances. In fact, I rarely use &lt;code&gt;eval()&lt;/code&gt; &lt;em&gt;at all&lt;/em&gt; to manipulate a JavaScript context except for loading source files into the interpreter.&lt;/p&gt;

&lt;p&gt;The Ruby API consists of &lt;code&gt;V8::Object&lt;/code&gt; and all of its subclasses:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;V8::Context.new do |cxt|
  cxt.eval(&amp;#39;new Object()&amp;#39;).class #=&amp;gt; V8::Object
  cxt.eval(&amp;#39;(function() {})&amp;#39;).class #=&amp;gt; V8::Function
  cxt.eval(&amp;#39;new Array()).class #=&amp;gt; V8::Array
end&lt;/code&gt;&lt;/pre&gt;

&lt;h2 id='objects'&gt;Objects&lt;/h2&gt;

&lt;p&gt;The most fundamental operations in dealing with JavaScript objects are the getting and setting of values. Coincidentally, this is also a fundamental concept in Ruby, so it comes as no great surprise that we can re-use those constructs in Ruby that deal with property access to mirror those same operations on their JavaScript counterparts: the &lt;code&gt;[]()&lt;/code&gt;/&lt;code&gt;[]=()&lt;/code&gt; and &lt;code&gt;foo()&lt;/code&gt;/&lt;code&gt;foo=()&lt;/code&gt; methods:&lt;/p&gt;

&lt;p&gt;given the following context:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;cxt = V8::Context.new
order = cxt.eval(&amp;#39;order = {eggs: &amp;quot;over-easy&amp;quot;}&amp;#39;)&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;we can read the &lt;code&gt;eggs&lt;/code&gt; property of our order in several differnt ways. Via hash access (note that both string and symbol are acceptable as key values):&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;order[&amp;#39;eggs&amp;#39;] #=&amp;gt; &amp;quot;over-easy&amp;quot;
order[:eggs] #=&amp;gt; &amp;quot;over-easy&amp;quot;&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Values can be set with the hash-style access as well, and changes made from Ruby will be reflected accordingly on the JavaScript side&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;order[&amp;#39;eggs&amp;#39;] = &amp;quot;sunny side up&amp;quot;
cxt.eval(&amp;#39;order.eggs&amp;#39;) #=&amp;gt; &amp;quot;sunny side up&amp;quot;&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;For property names that are also valid Ruby method names, you can access them just like you would with Ruby properties declared with &lt;code&gt;attr_reader&lt;/code&gt; or &lt;code&gt;attr_accessor&lt;/code&gt;. Again, changes made to the object in this way will be reflected in JavaScript:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;  order.eggs #=&amp;gt; &amp;quot;sunny side up&amp;quot;
  order.eggs = &amp;quot;scrambled&amp;quot;
  cxt.eval(&amp;#39;order.eggs&amp;#39;) #=&amp;gt; &amp;quot;scrambled&amp;quot;
end&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;In the cases where the property name is not a valid Ruby method name, hash-style access is mandatory:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;order[&amp;#39;Extra $%#@! Mayonaise!&amp;#39;] = true&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;&lt;code&gt;V8::Object&lt;/code&gt; also includes &lt;code&gt;Enumerable&lt;/code&gt; and allows you to access all properties of a given object.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;order.each do |key, value|
  puts &amp;quot;#{key} -&amp;gt; #{value}&amp;quot;
end

#outputs:
eggs -&amp;gt; scrambled
Extra $%#@! Mayonaise! -&amp;gt; true&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;As a convenience, &lt;code&gt;V8::Context&lt;/code&gt; delegates the hash access functions to the JavaScript object which serves as its global scope.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;order == cxt[&amp;#39;order&amp;#39;] #=&amp;gt; true
order == cxt.scope[&amp;#39;order&amp;#39;] #=&amp;gt; true&lt;/code&gt;&lt;/pre&gt;

&lt;h2 id='arrays'&gt;Arrays&lt;/h2&gt;

&lt;p&gt;Not much to see here, but before you move along: A &lt;code&gt;V8::Array&lt;/code&gt; is like every other &lt;code&gt;V8::Object&lt;/code&gt; except it has a &lt;code&gt;length&lt;/code&gt; property, and it enumerates over the items stored at indices instead of the key, value pairs of its properties.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;array = cxt.eval(&amp;#39;[&amp;quot;green&amp;quot;, &amp;quot;red&amp;quot;, &amp;quot;golden&amp;quot;]&amp;#39;)
array.length #=&amp;gt; 3
array.map {|color| &amp;quot;#{color} slumbers&amp;quot;} #=&amp;gt; [&amp;#39;green slumbers&amp;#39;, &amp;#39;red slumbers&amp;#39;, &amp;#39;golden slumbers&amp;#39;]&lt;/code&gt;&lt;/pre&gt;
&lt;a name='functions'&gt;

&lt;/a&gt;
&lt;h2 id='functions'&gt;Functions&lt;/h2&gt;

&lt;p&gt;Consider the classic &amp;#8220;Circle&amp;#8221; example from every object oriented playbook you&amp;#8217;ll ever read. In JavaScript, the way to implement the circle &amp;#8220;class&amp;#8221; is with a constructor function.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;circle = cxt.eval&amp;lt;&amp;lt;-JS
  function Circle(radius) {
    this.radius = radius
    this.area = function() {
      return this.radius * this.radius * Math.PI
    }
    this.circumference = function() {
      return 2 * Math.PI * this.radius
    }
  }
  new Circle(5)
JS&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now that we have the &lt;code&gt;Circle&lt;/code&gt; constructor defined, and we have a reference to an instance of it in Ruby, we can call its methods just as though it were a normal Ruby object. Of course, only we know that under the covers the implementation is actually in JavaScript:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;circle.class            #=&amp;gt; V8::Object
circle.radius           #=&amp;gt; 5
circle.area()           #=&amp;gt; 25Π
circle.circumference()  #=&amp;gt; 10Π&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;In JavaScript, methods are just object properties that happen to be functions. Therefore, you can get a reference to the actual function value just as you could from JavaScript simply by accessing the property by name. The resulting value is an instance of &lt;code&gt;V8::Function&lt;/code&gt;.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;area =                circle[&amp;#39;area&amp;#39;]
circumference =       circle[&amp;#39;circumference&amp;#39;]
area.class            #=&amp;gt; V8::Function
circumference.class   #=&amp;gt; V8::Function&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Once you have a reference to a &lt;code&gt;V8::Function&lt;/code&gt;, there are two ways to call the underlying JavaScript code (Actually there are three, but the third will be covered in the next section). These are the &lt;code&gt;call()&lt;/code&gt; and &lt;code&gt;methodcall()&lt;/code&gt; methods. To understand the difference between these two methods, it helps to understand how JavaScript functions themselves are invoked. In the event, there is the option to pass an object which will serve as the implicit invocant or &lt;code&gt;this&lt;/code&gt; value. If no &lt;code&gt;this&lt;/code&gt; is provided, the function will use the global scope in its place. Take for example the following JavaScript&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;var circle = new Circle(5)
var area = circle.area  //=&amp;gt; [object Function]
//no invocant, corresponds to ruby call()
area()  //=&amp;gt; NaN, there is no global &amp;#39;radius&amp;#39;.
//call with invocant, corresponds ruby methodcall()
area.apply(circle)  //=&amp;gt; 25Π&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The same code in Ruby:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;area = circle[&amp;#39;area&amp;#39;]
area.class              #=&amp;gt; V8::Function
area.call()             #=&amp;gt; NaN
area.methodcall(circle) #=&amp;gt; 25Π&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Because of this mechanism, JavaScript method invocation is much more flexible than Ruby in the sense that virtually &lt;em&gt;any&lt;/em&gt; object can be used as the invocant of &lt;em&gt;any&lt;/em&gt; function provided it has the requisite properties to satisfy the function&amp;#8217;s requirements:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;area.methodcall(:radius =&amp;gt; 5) #=&amp;gt; 25Π
other_circle = OpenStruct.new
other_circle.radius = 10
area.methodcall(other_circle) #=&amp;gt; 100Π&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;A very powerful construct indeed.&lt;/p&gt;

&lt;h2 id='constructors'&gt;Constructors&lt;/h2&gt;

&lt;p&gt;But wait, there&amp;#8217;s more! Any JavaScript function can be either invoked normally, or, combined with the &lt;code&gt;new&lt;/code&gt; keyword, as a &lt;em&gt;constructor&lt;/em&gt;. It&amp;#8217;s what we used in the original eval() block to create the instance of &lt;code&gt;Circle&lt;/code&gt; whose methods we were messing about with.&lt;/p&gt;

&lt;p&gt;That was not quite necessary since we can invoke functions as constructors from Ruby too. This is done with the &lt;code&gt;new&lt;/code&gt; method of &lt;code&gt;V8::Function&lt;/code&gt;.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;Circle = cxt[&amp;#39;Circle&amp;#39;]
circle2 = Circle.new(3)
circle2.radius        #=&amp;gt; 3
circle2.area          #=&amp;gt; 9Π
circle2.circumference #=&amp;gt; 6Π&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Interestingly, when used as a constructor, a JavaScript function is almost completely indistinguishable from a Ruby class. This apparent duality between classes and functions is behind the decision to &lt;a href='/2010/06/30/accessing-ruby-objects-from-V8#classes'&gt;represent Ruby classes reflected into JavaScript as functions&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The driving goal in all of these cases is the ability to author intuitive, tightly bound JavaScript, which necessarily doesn&amp;#8217;t involve evaluating strings to get what you want done. In closing, if there is something missing from this API you think would be useful, I would love to &lt;a href='http://github.com/cowboyd/therubyracer/issues'&gt;hear about it&lt;/a&gt;&lt;/p&gt;</content>



 </entry>
 
 <entry>
   <title>Accessing Ruby Objects From V8</title>
   <link href="/2010/06/30/accessing-ruby-objects-from-V8/"/>
   <updated>Liquid error: undefined method `xmlschema' for "30 June 2010":String</updated>
   <id>/2010/06/30/accessing-ruby-objects-from-V8</id>
   <content type="html">&lt;p&gt;The upcoming version of &lt;a href='http://github.com/cowboyd/therubyracer'&gt;The Ruby Racer&lt;/a&gt; will see some significant changes to the way Ruby objects are reflected into the javascript runtime and how you the programmer can control the way that those ruby objects appear.&lt;/p&gt;

&lt;p&gt;Most of these changes were precipitated from the experience of integrating The Ruby Racer with the &lt;a href='http://github.com/aslakhellesoy/rednode'&gt;Rednode&lt;/a&gt; and &lt;a href='http://github.com/svenfuchs/rdom'&gt;RDom&lt;/a&gt; projects. Both efforts have run up against the shortcomings in the way Ruby objects are embedded into JavaScript, and as a result have both had a large hand in crafting the improvements which I&amp;#8217;m about to describe. Many thanks got to &lt;a href='http://blog.aslakhellesoy.com/'&gt;Aslak Hellesoy&lt;/a&gt; and &lt;a href='http://www.artweb-design.de/svenfuchs'&gt;Sven Fuchs&lt;/a&gt; for helping to flush out all the various issues.&lt;/p&gt;

&lt;p&gt;In picking the default strategy, there were three principles that I wanted to adhere to&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Do what I mean&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The JavaScript object representing your Ruby object should behave as closely as what you intend with the Ruby object itself. In other words, properties should be properties. Methods should be methods. Public properties and methods should be public, while private properties and methods should be private.&lt;/p&gt;
&lt;/li&gt;

&lt;li&gt;
&lt;p&gt;&lt;strong&gt;No new syntax required&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Ruby has a rich and flexible syntax for describing how objects behave. Instead of introducing a new syntax by way of a DSL describing how those objects behave inside a javascript runtime, I wanted to borrow/re-use as much of the Ruby syntax as possible. This may prove to be a difficult goal to achieve going forward given that the two runtimes do differ in many significant ways. Nevertheless, I want to see how far plain old ruby semantics can take us.&lt;/p&gt;
&lt;/li&gt;

&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Safe by default&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;JavaScript has been used since its earliest beginnings to provide a eval-safe sandbox in which anonymous code can be executed without posing any danger to the host system. To enable this type of development, one of the design goals of The Ruby Racer is for developers to be have the freedom to build their JavaScript environments confident that the framework won&amp;#8217;t introduce silently introduce dangerous security holes. Unsafe behavior must be explicitly included into the default JavaScript runtime.&lt;/p&gt;
&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id='basic_access'&gt;Basic Access&lt;/h2&gt;

&lt;p&gt;To call a Ruby object from javascript, assign a name to it in the context. The following code assigns a new instance of the class &lt;code&gt;Foo&lt;/code&gt; to the name &lt;code&gt;f&lt;/code&gt;.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;class Foo
  def foo(count)
    &amp;quot;foo&amp;quot; * count
  end
end
cxt = V8::Context.new
f = Foo.new
cxt[&amp;#39;f&amp;#39;] = f&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;We can now access this object from within JavaScript&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;cxt.eval(&amp;#39;f.foo(2)&amp;#39;) #=&amp;gt; &amp;quot;foofoo&amp;quot;&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Ruby procs and methods can also be directly embedded into javascript and will behave just like a function&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;cxt[&amp;#39;foo&amp;#39;] = proc {|times| f.foo(times)}
cxt[&amp;#39;footoo] = f.method(:foo)

cxt.eval(&amp;#39;foo(3)&amp;#39;) #=&amp;gt; &amp;quot;foofoofoo&amp;quot;
cxt.eval(&amp;#39;footoo(1)&amp;#39;) #=&amp;gt; &amp;quot;foo&amp;quot;&lt;/code&gt;&lt;/pre&gt;

&lt;h2 id='properties_vs_methods'&gt;Properties vs. Methods&lt;/h2&gt;

&lt;p&gt;In JavaScript, everything is just a property on an object. Methods are just properties that happen to be functions. In Ruby on the other hand, properties and methods are indistinguishable. A property is just a method without any arguments, so The Ruby Racer re-uses this convention for reflecting Ruby objects into JavaScript. That is to say if a Ruby method takes no arguments, then it will look like a JavaScript property.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;class Random
  def number
    (Kernel.rand * 100).to_i
  end
end

cxt[&amp;#39;random&amp;#39;] = Random.new
cxt.eval(&amp;#39;random.number&amp;#39;) #=&amp;gt; 80
cxt.eval(&amp;#39;random.number&amp;#39;) #=&amp;gt; 77&lt;/code&gt;&lt;/pre&gt;

&lt;h3 id='property_assignment'&gt;Property assignment&lt;/h3&gt;

&lt;p&gt;Properties aren&amp;#8217;t always read only. When you want to assign to them, The Ruby Racer uses standard Ruby assigment methods&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;class Doubler
  def number
    @number ||= 2
  end
  
  def number=(value)
    @number = value * 2
  end
end

cxt[&amp;#39;doubler&amp;#39;] = Doubler.new
cxt.eval(&amp;#39;doubler.number = 5&amp;#39;)
cxt.eval(&amp;#39;doubler.number&amp;#39;) #=&amp;gt; 10&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Which mean for standard run of the mill Ruby properties, you can use plain old &lt;code&gt;attr_accessor&lt;/code&gt;, just like Matz intended&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;class NotFancy
  attr_accessor :pants
end

plain = NotFancy.new
cxt[&amp;#39;plain&amp;#39;] = plain
cxt.eval(&amp;#39;plain.pants = &amp;quot;blue&amp;quot;&amp;#39;)
puts plain.pants #=&amp;gt; &amp;quot;blue&amp;quot;
plain.pants = &amp;quot;green&amp;quot;
cxt.eval(&amp;#39;plain.pants&amp;#39;) #=&amp;gt; &amp;quot;green&amp;quot;&lt;/code&gt;&lt;/pre&gt;

&lt;h3 id='methods_with_no_arguments'&gt;Methods with No Arguments&lt;/h3&gt;

&lt;p&gt;There are some cases however, where you want a zero-argument Ruby method to &lt;em&gt;not&lt;/em&gt; look like a property. Most of the time these represent definite actions that can be invoked (&lt;code&gt;this.dequeue()&lt;/code&gt;, &lt;code&gt;stack.clear()&lt;/code&gt;, etc&amp;#8230;) as opposed to state that can be read (e.g. &lt;code&gt;array.length&lt;/code&gt;). For this case, make a getter that returns a function.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;class Mouth
  def sayHello()
    proc do
      &amp;quot;Hello&amp;quot;
    end
  end
end

cxt[&amp;#39;mouth&amp;#39;] = Mouth.new
cxt.eval(&amp;#39;mouth.sayHello&amp;#39;) #=&amp;gt; [object Function]
cxt.eval(&amp;#39;mouth.sayHello()&amp;#39;) #=&amp;gt; &amp;quot;Hello&amp;quot;&lt;/code&gt;&lt;/pre&gt;

&lt;h3 id='dynamically_declaring_properties'&gt;Dynamically Declaring Properties&lt;/h3&gt;

&lt;p&gt;A highly meta-programming enabled language like Ruby means that methods are often generated by code and not by the programmer. If you&amp;#8217;re going to generate methods that will be called from JavaScript, then it is important that you be able to control whether they appear as properties or functions. By default, Ruby &lt;code&gt;Proc&lt;/code&gt; objects have an arity of -1 (meaning variadic arguments)which means that JavaScript will see them as a function and not a property.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;class Foo
  self.send(:define_method, :bar) do
    &amp;quot;bar!&amp;quot;
  end
end
cxt[&amp;#39;foo&amp;#39;] = Foo.new
cxt.eval(&amp;#39;foo.bar&amp;#39;) #=&amp;gt; [object Function]
cxt.eval(&amp;#39;foo.bar()) #=&amp;gt; bar!&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;To make the method appear as a property, you must explicitly tell ruby that the block takes no arguments by declaring it with &amp;#8220;empty pipes&amp;#8221;&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;class Foo
  self.send(:define_method, :baz) do || #&amp;lt;--- empty pipes
    &amp;quot;baz!&amp;quot;
  end
end

cxt.eval(&amp;#39;foo.baz&amp;#39;) #=&amp;gt; baz!&lt;/code&gt;&lt;/pre&gt;

&lt;h2 id='intercepting_property_access'&gt;Intercepting Property Access&lt;/h2&gt;

&lt;p&gt;What happens if you want to implement properties so dynamic that you won&amp;#8217;t know if they are defined until you actually try to access them? This is actually very common in Ruby. If it cannot find a method for particular object, it will invoke its method_missing() method and allow it to provide a suitable implementation at the very moment of dispatch!&lt;/p&gt;

&lt;p&gt;This usually happens when you use information encoded in the property name as part of the property definition as in &lt;code&gt;ActiveRecord&lt;/code&gt; finders such as &lt;code&gt;find_by_job_description&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;The Ruby Racer provides a similar mechanism to allow Ruby objects to define properties at access time. When you attempt to access a property of a Ruby object from JavaScript, it will first look to see if there is a pre-defined property. If not, it will then check to see if the object has defined a Ruby &amp;#8220;hash access&amp;#8221; method &lt;code&gt;[]()&lt;/code&gt;. If so, it will invoke that method with the missing property name in order that the object can provide any implementation.&lt;/p&gt;

&lt;p&gt;Let&amp;#8217;s say for example that you wanted to dynamically define properties that returned a list of process for a given user.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;class Processes
  def [](name)
    `ps -U #{name} -o pid`.split(&amp;quot;\n&amp;quot;)
  end
end

cxt[&amp;#39;processes&amp;#39;] = Processes.new
cxt.eval(&amp;#39;processes.cowboyd&amp;#39;) #=&amp;gt; [&amp;quot;205&amp;quot;, &amp;quot;209&amp;quot;, &amp;quot;210&amp;quot;, .....]
cxt.eval(&amp;#39;processes.root&amp;#39;) #=&amp;gt; [&amp;quot;1&amp;quot;, &amp;quot;10&amp;quot;, &amp;quot;11&amp;quot;, &amp;quot;12&amp;quot;, .....]
cxt.eval(&amp;#39;processes.no_such_user&amp;#39;) #=&amp;gt; []&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;In a similar fashion, you can use the Ruby hash setter method &lt;code&gt;[]=()&lt;/code&gt; in order to intercept property setting&lt;/p&gt;

&lt;h2 id='id1'&gt;&lt;a name='classes'&gt;Embedding Classes&lt;/a&gt;&lt;/h2&gt;

&lt;p&gt;In may come about that you want to embed an actual Ruby Class object into your JavaScript enviroment. JavaScript does not have the concept of classes, so we have to choose the best representation we can. The most natural way to do this is by treating a Ruby class as a constructor function. It behaves just like any other object embedded into ruby except that by default the Ruby Racer treats them as &lt;em&gt;constructor functions&lt;/em&gt;. You can call the constructor in order to create instances of your ruby class and use them from JavaScript&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;class Point
  attr_reader :x,:y
  def initialize(x, y)
    @x, @y = x, y
  end
  
  def to_s
    &amp;quot;(#{x},#{y})&amp;quot;
  end
end

cxt[&amp;#39;Point&amp;#39;] = Point
cxt.eval(&amp;#39;new Point(1,2)&amp;#39;) #=&amp;gt; (1,2)&lt;/code&gt;&lt;/pre&gt;

&lt;h2 id='where_it_looks_for_methodsproperties'&gt;Where it Looks for Methods/Properties&lt;/h2&gt;

&lt;p&gt;Finally, when The Ruby Racer is trying to find a method or property on an object, it does not search &lt;em&gt;all&lt;/em&gt; of the object&amp;#8217;s public methods, but only a subset. This is because there are many potentially dangerous methods on every single Ruby object (such as &lt;code&gt;eval()&lt;/code&gt;), and the Ruby Racer should tend towards safety. For that reason, The Ruby Racer provides access to all methods in a class&amp;#8217;s list of ancestors up to but not including Object.&lt;/p&gt;

&lt;p&gt;This includes any included or extend modules by an object&amp;#8217;s class and superclasses (except those included by Object and above). e.g.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;module A
  def a 
    &amp;quot;a&amp;quot; 
  end
end
class B
  include A
  def b 
    &amp;quot;b&amp;quot;
  end
end
class C &amp;lt; B
  def c
    &amp;quot;c&amp;quot;
  end
end
module D
  def d
    &amp;quot;d&amp;quot;
  end
end
class Object
  include D
end

cxt[&amp;#39;c&amp;#39;] = C.new
cxt.eval(&amp;#39;c.a&amp;#39;) #=&amp;gt; a
cxt.eval(&amp;#39;c.b&amp;#39;) #=&amp;gt; b

cxt.eval(&amp;#39;c.d&amp;#39;) #=&amp;gt; nil
cxt.eval(&amp;#39;c.to_s&amp;#39;) #=&amp;gt; nil&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;That&amp;#8217;s about it. The Ruby Racer aims for accessing Ruby objects and methods to be &lt;em&gt;intuitive&lt;/em&gt;, &lt;em&gt;simple&lt;/em&gt;, and &lt;em&gt;safe&lt;/em&gt; so that you can focus on creating your ideal embedding.&lt;/p&gt;</content>



 </entry>
 
 <entry>
   <title>Rye Repeat Yourself Enough</title>
   <link href="/2009/06/29/rye-repeat-yourself-enough/"/>
   <updated>Liquid error: undefined method `xmlschema' for "29 Jun 2009":String</updated>
   <id>/2009/06/29/rye-repeat-yourself-enough</id>
   <content type="html">&lt;p&gt;Lately, I&amp;#8217;ve been practicing the exact opposite of the DRY principle. Yup, you read that right: I repeat myself constantly, and in as many different contexts&amp;#8230; including code, database schemas, test-plans and even documentation. The reason: So I won&amp;#8217;t have to repeat myself. It&amp;#8217;s not that I don&amp;#8217;t buy into the DRY principle, or that I&amp;#8217;m somehow skeptical about the value its proper application yields. I just find it difficult to achieve in practice.&lt;/p&gt;

&lt;p&gt;According to the &lt;a href='pragmaticprogrammer.com'&gt;Pragmatic Programmers&lt;/a&gt; who coined the term:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;DRY says that every piece of system knowledge should have one authoritative, unambiguous representation. Every piece of knowledge in the development of something should have a single representation. A system&amp;#8217;s knowledge is far broader than just its code. It refers to database schemas, test plans, the build system, even documentation.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Essentially it is an empirical measure against which to gauge the proper level of abstraction in your system. If you have not made the right abstractions, then you will be found to be repeating yourself, whereas if you &lt;em&gt;have&lt;/em&gt; made the right abstractions, then you won&amp;#8217;t. This is because abstractions &lt;em&gt;directly encode&lt;/em&gt; the system knowledge that DRY talks about no less than 3 times in its definition.&lt;/p&gt;

&lt;p&gt;The benefits of good abstractions are many and well known, and I&amp;#8217;m not going to go into them here (there&amp;#8217;s always the internet for that), but what I&amp;#8217;ve taken particular heed of lately is that abstraction is a double-edged sword that should not be wielded lightly. Get it right, and the previously intractable dissolves to simplicity in an instant&amp;#8230; but get it wrong, and a snarl of complexity gridlocks your code base just as fast.&lt;/p&gt;

&lt;p&gt;You see, I wasn&amp;#8217;t telling the whole truth when I said before that abstractions directly encode system knowledge. It would be more correct to say: &lt;em&gt;Good&lt;/em&gt; abstractions directly encode system knowledge. &lt;em&gt;Bad&lt;/em&gt; abstractions directly encode &lt;em&gt;system ignorance.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;The problem is that the DRY principle, while still very valid and useful, doesn&amp;#8217;t help us here because it assumes system knowledge as its input. But really valuable system knowledge isn&amp;#8217;t just lying around, it must be carefully constructed with significant amounts of research and analysis. That is to say, it must be learned. And what better way is there to learn something than by doing it over and over again until you know it inside and out? What better way is there than trial and error to really &lt;em&gt;get at the physics&lt;/em&gt; of a phenomenon until you can use it to easily analyze it in all its forms? The fact is, you&amp;#8217;ve got to repeat yourself over and over enough times until you can say with confidence: &lt;em&gt;This I know to be true.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;You can think of it like doing your math homework, or being like Daniel-San: waxing Mr Miyagi&amp;#8217;s car again and again until you know karate by instinct. In fact, I&amp;#8217;m convinced that there&amp;#8217;s no other way to generate &lt;em&gt;real&lt;/em&gt; knowledge.&lt;/p&gt;

&lt;p&gt;Ironically, I repeat myself a lot these days because I hate repeating myself. I loathe it with an almost pathological passion, and sometimes (more often then I&amp;#8217;d like to admit) it plays to my disadvantage. In my obsessive/compulsive rush to not repeat myself I&amp;#8217;ll introduce a bad abstraction based on flawed or incomplete system knowledge, and worse still, I won&amp;#8217;t know that I took the wrong fork in the road until it&amp;#8217;s way late in the game and it&amp;#8217;s hard to find the way back home.&lt;/p&gt;

&lt;p&gt;That&amp;#8217;s why I&amp;#8217;m playing it cool lately and making sure that I repeat myself enough to &lt;em&gt;perfect&lt;/em&gt; the system knowledge required to keep myself DRY.&lt;/p&gt;</content>



 </entry>
 
 <entry>
   <title>In Search Of A Better Autogrowing Textfield</title>
   <link href="/2008/12/16/in-search-of-a-better-autogrowing-textfield/"/>
   <updated>Liquid error: undefined method `xmlschema' for "16 Dec 2008":String</updated>
   <id>/2008/12/16/in-search-of-a-better-autogrowing-textfield</id>
   <content type="html">&lt;p&gt;Autogrowing textfields are a nice piece of flash for any web application. They conserve precious screen real-estate, but grow to a height just big enough to accomodate the text the user actually typed without resorting to unsightly things scrollbars.&lt;/p&gt;

&lt;p&gt;There are a number of solutions out there, but since I&amp;#8217;m using &lt;a href='http://jquery.com' target='_blank'&gt;jQuery&lt;/a&gt; on my current project, the two that I evaluated were &lt;a href='http://plugins.jquery.com/project/Growfield' target='_blank'&gt;Growfield&lt;/a&gt; and &lt;a href='http://plugins.jquery.com/project/Autogrow' target='_blank'&gt;Autogrow&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;While those two plugins often did what they were supposed to do, they also had tons of quirks and edge cases that prompted me give it a go myself. Specifically, I found that depending on the browser and operating system I would encounter:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;eye-jarring jitter wherein the textfield would expand and contract my 1 or 2 pixels with every keystroke&amp;lt;/li&amp;gt;&lt;/li&gt;

&lt;li&gt;resizing of the textfield to 0 pixels, when there was no text in the box&lt;/li&gt;

&lt;li&gt;intermittent loss of focus on some browsers&amp;lt;/li&amp;gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;But most importantly, it seemed that more often than not, the text did not actually grow correctly in any of the real-world environments that I tried in my production application.&lt;/p&gt;

&lt;p&gt;As I discovered, the main reason for this was that the technique used was to fill a hidden DIV element with the text from the textfield, and then use the height of that DIV to determine how tall the textfield should be. That works great except for one nasty detail: most browsers use native widgets for text inputs, and those native widgets have their own word-wrap and layout code, so even things like font, line-height and letter spacing being equal, you can still get different word-wrap behavior from OS to OS.&lt;/p&gt;

&lt;p&gt;In an attempt to side-step all of these issues, I thought &amp;#8220;what if instead of using a DIV element to calculate the height, I could use a native textfield?&amp;#8221; After all, if native textfields use a different word-wrap and layout algorithms, can&amp;#8217;t I just try and harness those algorithms, whatever they might be? At first this seems perfectly circular i.e.: I don&amp;#8217;t know what the ideal height of a textarea should be, so I&amp;#8217;ll use the height of a texarea to find out. Of course there&amp;#8217;s a twist, and the wonderful little property that makes it all possible is the &lt;a href='https://developer.mozilla.org/en/DOM/element.scrollHeight' target='_blank'&gt;scrollHeight&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;lines, not heights.&lt;/p&gt;</content>



 </entry>
 
 <entry>
   <title>Please Stop Using Global Variables In Ruby</title>
   <link href="/2008/06/25/please-stop-using-global-variables-in-ruby/"/>
   <updated>Liquid error: undefined method `xmlschema' for "25 Jun 2008":String</updated>
   <id>/2008/06/25/please-stop-using-global-variables-in-ruby</id>
   <content type="html">&lt;p&gt;I couldn&amp;#8217;t sleep this morning. I woke up around 4:30 AM thinking about how code is organized in ruby. I&amp;#8217;m sure I will look back on my life with disbelief and a touch of shame at such behavior, but that is (hopefully) decades away.&lt;/p&gt;

&lt;p&gt;The problem turning around in my head which eventually caused me to wake was my own inability to come to terms with a prevalent pattern in the ruby community: the global variable. Swirling in my semi-conscious mind was a motley mixture of bewilderment, self-doubt, scorn and a touch of righteous indignation.&lt;/p&gt;

&lt;p&gt;On the one hand, there must be something I&amp;#8217;m missing. One of the reasons I love ruby-space is that it tends to be filled with talented programmers who work the language to produce code that is powerful while at the same time being easy to understand and use. Surely, their collective conscious is a better guide than my own experience and intuition. I worry that is primarily my own fuddy-duddity that prevents me from accepting global variables as good practice.&lt;/p&gt;

&lt;p&gt;To clarify, when I speak about global variables, I&amp;#8217;m talking primarily about using global class objects as the repositories for methods and state. There are plenty examples out there of this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;# active record
Post.find(:all)

# amazon s3
S3Object.store(&amp;#39;me.jpg&amp;#39;, open(&amp;#39;headshot.jpg&amp;#39;), &amp;#39;photos&amp;#39;)

# paypal-business gem
Paypal.capture(params)&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;In each of the preceding examples, there is implicit state stored on the class object. In active record, the database connection information, in S3Object, the AWS access key id and secret key, and finally, in Paypal, the paypal server url and business account name. Because the class object is global, the state on it is effectively global. And &lt;em&gt;that&lt;/em&gt; is what sets my spidey sense to tingling.&lt;/p&gt;

&lt;p&gt;Not only is this style subject to the all the arguments for why &lt;a href='http://c2.com/cgi/wiki?GlobalVariablesAreBad'&gt;global variables are bad&lt;/a&gt;, but it just flat-out makes the API&amp;#8217;s themselves less useful. Here&amp;#8217;s an example from an actual project.&lt;/p&gt;

&lt;p&gt;I had a system which needed to talk to two different SQS queues which were contained in two separate amazon web services accounts. Unfortunately, the standard SQS api uses class variables to store configuration information, and then a set of class methods to access the queue services, so I was forced to overwrite the global configuration parameters every time I wanted to access the queue. Luckily, the application was not multi threaded, or I would have been stuck rolling my own.&lt;/p&gt;

&lt;p&gt;I don&amp;#8217;t see why:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;SQS.access_key_id = &amp;#39;ACCESS_ID&amp;#39;
SQS.secret_access_key = &amp;#39;SECRET&amp;#39;
q = SQS.get_queue &amp;#39;MyQueue&amp;#39;&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;is any better than:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;@sqs = SQS.new :access_key_id =&amp;gt; &amp;#39;ACCESS_ID&amp;#39;, :secret_access_key =&amp;gt; &amp;#39;SECRET&amp;#39;
q = @sqs.get_queue &amp;#39;MyQueue&amp;#39;&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;(IMHO it&amp;#8217;s uglier) and in the second, hypothetical API, you can painlessly, and in a thread-safe manner talk to multiple queues on multiple accounts.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;@one = SQS.new :access_key_id =&amp;gt; &amp;#39;AccountOne&amp;#39;, :secret_access_key =&amp;gt; &amp;quot;AccountOneSecret&amp;quot;
@two = SQS.new :access_key_id =&amp;gt; &amp;#39;AccountTwo&amp;#39;, :secret_access_key =&amp;gt; &amp;quot;AccountTwoSecret&amp;quot;&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;But there&amp;#8217;s a deeper principle at stake here than allowing multiple instances. It&amp;#8217;s about giving &lt;em&gt;power to the programmer&lt;/em&gt;, and letting them control the API, and not the other way around.&lt;/p&gt;

&lt;p&gt;It seems to me that when you&amp;#8217;re designing an API, you want the programmer(to the greatest extent possible) be able to create their own little world over which they have complete control. The should be able to spin up as many instances of your code and use it in ways that perhaps you hadn&amp;#8217;t thought of without them having to worry that one world will interfere with another world they&amp;#8217;ve created.&lt;/p&gt;

&lt;p&gt;If you&amp;#8217;ve absolutely got to go global, it&amp;#8217;s very little effort to wrap a static/global interface around a single default instance, but not the other way around. Given the similarity in effort, it seems like embedability is the way to go.&lt;/p&gt;

&lt;p&gt;Global variables surely have their place in some applications, and I&amp;#8217;m not opposed to them on purely ideological grounds, but ruby already has a construct for global variables&amp;#8230; it&amp;#8217;s called the &amp;#8217;$&amp;#8217; sigil.&lt;/p&gt;

&lt;p&gt;In your environment.rb, or wherever you can just put:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;#environment.rb
$sqs = SQS.new :access_key_id =&amp;gt; &amp;#39;AccountOne&amp;#39;, :secret_access_key =&amp;gt; &amp;quot;AccountOneSecret&amp;quot;

#somewhere else
q = $sqs.get_queue &amp;quot;MyQueue&amp;quot;&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;My suspicion is that Ruby on Rails shares a large portion of the blame for the evolution of this style what with &lt;code&gt;ActiveRecord.establish_connection()&lt;/code&gt; and friends. As the highest profile ruby project it&amp;#8217;s only natural that people will copy its conventions &amp;#8211;for better or for worse. Still, I wish people in the future would break from this particular precedent and if they go global, to do it properly. Give the poor class objects a break!&lt;/p&gt;</content>



 </entry>
 
 <entry>
   <title>Patiently Waiting For Javafx Script</title>
   <link href="/2008/06/05/patiently-waiting-for-javafx-script/"/>
   <updated>Liquid error: undefined method `xmlschema' for "Thu Jun 05 11:22:05 -0500 2008":String</updated>
   <id>/2008/06/05/patiently-waiting-for-javafx-script</id>
   <content type="html">&lt;p&gt;About a year ago, SUN announced a &amp;#8220;new&amp;#8221; platform for developing embeddable applications on the web, and they called this platform JavaFX. In reality, this new platform seems to me less of an innovation and more of a rehabilitation of the applet infrastructure which they allowed to languish over the last decade.&lt;/p&gt;

&lt;p&gt;That&amp;#8217;s not a criticism, it&amp;#8217;s a compliment. I&amp;#8217;m happy that they&amp;#8217;re going to give applets another go. Heck, I&amp;#8217;m even glad they&amp;#8217;re calling it JavaFX too. &amp;#8220;Applet&amp;#8221; always sounded too effete anyway. In any case I&amp;#8217;ve always like the applet model, and wished it were a more viable option for web development. Given the success of Flex, which also uses the applet model, other people must feel this way too.&lt;/p&gt;

&lt;p&gt;But I digress.&lt;/p&gt;

&lt;p&gt;As far as I can tell (I&amp;#8217;ve only been able to get my hands on some demos and a little open source compiler) JavaFX involves upgrading some of the more boorish aspects of the java browser plugin. To name a few: faster download and initialization of application and JRE code, tighter integration and communication with the rest of the DOM, modern video and audio codecs&amp;#8230;. All those are necessary upgrades to ensure the viability of the platform, but they can hardly be called innovative&lt;/p&gt;

&lt;p&gt;That said, one new and curious aspect of JavaFX is that it will (for the most part) &lt;em&gt;not&lt;/em&gt; be written in Java. Instead, SUN is promoting a completely new and aptly named scripting language: JavaFX script.&lt;/p&gt;

&lt;p&gt;Of all the new features it was the specification of this language that impressed me most. I&amp;#8217;m not sure how this little gem of a language managed to come out of SUN, but it&amp;#8217;s absolutely loaded with modern language features to make programming in it clear and concise.&lt;/p&gt;

&lt;p&gt;I&amp;#8217;m talking about &lt;ul&gt;
&lt;li&gt;closures&lt;/li&gt;
&lt;li&gt;pure functions&lt;/li&gt;
&lt;li&gt;lazy evaluation&lt;/li&gt;
&lt;li&gt;list comprehensions (that put ruby's to shame)&lt;/li&gt;
&lt;li&gt;optional declarative syntax&lt;/li&gt;
&lt;li&gt;rolled in query language for searching and modifying data structures&lt;/li&gt;
&lt;li&gt;data binding supported at the language level&lt;/li&gt;
&lt;li&gt;tons of stuff I'm sure I don't even know about....&lt;/li&gt;
&lt;/ul&gt;&lt;/p&gt;

&lt;p&gt;Overall it seems like JavaFX script is like 4 separate languages existing in harmony in one neat package, and as I read more and more about it, I kept thinking to myself &amp;#8220;This is not just some standard UI scripting language with a little sugar and a few extra hooks for writing GUIs. This is positively &lt;em&gt;avante-garde&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;I like the idea that SUN can challenge their developers to think in new ways, but I can also imagine a backlash, or more mildly put, an general aversion in the developer community, since this is not any old language research project, but the centerpiece in SUN&amp;#8217;s product in the battle over the browser VM.&lt;/p&gt;

&lt;p&gt;So where did this decision come from to go with such a departure from the norm when it came to defining JavaFX script? I like it alot, but I worry that SUN is going to chicken out, and go with something a little less sexy but a little more digestible (at least in the short term) to its current developers as well as the developers of competing platforms like Adobe Flex or Microsoft Silverlight.&lt;/p&gt;</content>



 </entry>
 
 <entry>
   <title>When Using Mod Rewrite Remember That The Version Counts</title>
   <link href="/2007/06/11/when-using-mod-rewrite-remember-that-the-version-counts/"/>
   <updated>Liquid error: undefined method `xmlschema' for "Mon Jun 11 13:11:05 -0500 2007":String</updated>
   <id>/2007/06/11/when-using-mod-rewrite-remember-that-the-version-counts</id>
   <content type="html">&lt;pre&gt;&lt;code&gt;RewriteRule ^archives/(\d+).html http://www.thefrontside.net/map2new.php?$1 [R]&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;I wanted to match files like archives/000532.html.&lt;/p&gt;

&lt;p&gt;But when it came time to deploy, it didn&amp;#8217;t work. Turns out the environment I was deploying to was using a different version of Apache. That&amp;#8217;s bad practice of course, but aside from that, the little gotcha was that the regular expression interpreter was different in different versions of Apache, and in this case, its behavior differed not only from the newer version but also from the behavior of most regexp engine&amp;#8217;s out there. Specifically, the &amp;#8220;digit&amp;#8221; literal &lt;code&gt;\d&lt;/code&gt; is not understood by older versions (which interpret it as a literal &amp;#8220;d&amp;#8221;).&lt;/p&gt;

&lt;p&gt;Instead I had to use [0-9]&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;RewriteRule ^archives/([0-9]+).html http://www.thefrontside.net/map2new.php?$1 [R]&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This is a very specific nugget, but hopefully it will save someone a headache down the road. Just remember, if your mod_rewrite regexp isn&amp;#8217;t working, &lt;em&gt;check the specific version of the engine&lt;/em&gt;, and make sure your regexp is one that it will understand.&lt;/p&gt;</content>



 </entry>
 
 <entry>
   <title>The Chicken And The Vine Trans Global Pair Programming</title>
   <link href="/2007/06/08/the-chicken-and-the-vine-trans-global-pair-programming/"/>
   <updated>Liquid error: undefined method `xmlschema' for "Sat Jun 09 00:07:14 -0500 2007":String</updated>
   <id>/2007/06/08/the-chicken-and-the-vine-trans-global-pair-programming</id>
   <content type="html">&lt;p&gt;The Frontside Software is a three person company with &quot;offices&quot; in Michigan, Finland, Massachusetts, and New Jersey. We're don't see each other every day, and we're rarely in the same room, but we still do a significant portion of our development work in pairs. Despite many other competing setups, we still do this with the not-so-new, not-so-exciting, yet extremely flexible and reliable &lt;a href='http://www.realvnc.com/what.html' title='Real VNC'&gt;VNC&lt;/a&gt; combined with a voip product like &lt;a href='http://skype.com' title='Skype VOIP'&gt;skype&lt;/a&gt;.&lt;/p&gt;&lt;h3&gt;How it works&lt;/h3&gt;&lt;p&gt;One of us (the driver) runs a vnc server which transmits everything that is rendered on his display to one or more vnc clients (passengers) being run by the other half of the pair. That way, the client can see everything that goes on while the driver is coding, including  his code editor, his web browser, his terminal windows, etc... Meanwhile, you've got real-time audio so that you can talk about the work you're doing as you're doing it.&lt;/p&gt;&lt;h3&gt;Is there something better?&lt;/h3&gt;&lt;p&gt;Not yet. We've seen some new collaborative coding tools like &lt;a href='http://www.codingmonkeys.de/subethaedit/' title='SubEthaEdit Site'&gt;SubEthaEdit&lt;/a&gt; and &lt;a href='http://gobby.0x539.de/trac/' title='Gobby Trac Site'&gt;Gobby&lt;/a&gt; come down with some very slick features. Specifically, the updating and syncing of editor state between the two machines is very fast, and effectively coordinates multiple people editing the same document, with as few clashes as possible. The way in which they do this is impressive, but after having given it several abortive attempts as a real solution for remote pair programming, we went back to good old VNC. Here's why:&lt;/p&gt;&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Lack of editing features:&lt;/strong&gt; The collaborative editors of today are good at one thing: editing text collaboratively. The problem is that when you're pair-programming, you're not editing text, you're editing code, and code is only a simple sequence of text to a computer. There are lots of editors these days that leverage the semantically rich structure of the documents on which they operate like TextMate, Emacs, Eclipse.... everybody has a favorite, and because your collaborative editor is not your favorite, that means it sucks ;-)&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Lack of environment:&lt;/strong&gt; Of course, there are a scant few collaborative editing plug-ins for existing IDEs which would seem to address this problem, but adding on another layer, development is about more than just coding. It's about browsing documentation, running servers, invoking build scripts from the command line, and about a million other tiny tasks. In effect, your &lt;em&gt;actual&lt;/em&gt; IDE is not just one application, it's your whole computer, and if the only thing being shared is a single app, then it cuts your pair out of a lot of important context. With VNC, everybody sees what's going on all the time. They can see not only the code, but also the running program.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Editing the same document at the same time isn't really helpful anyway&lt;/strong&gt;: If you've done much pair-programming, then you realize that the real value doesn't come from having two sets of fingers on the keyboard at the same time. In fact quite the opposite: Both participants are following the thread of development, but one of them is freed entirely from the act of coding so that they can think about high-level architectural issues, or lookup api docs, or google for resources --all in parallel. Having both people pounding on the keyboard actually hinders this dynamic.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;VNC is cross platform&lt;/strong&gt;: This is a biggie. There are vnc clients and servers for Windows, OSX, and Linux (we code on all three), and they all interoperate with each other. That's a pretty hard feature to top, especially for single-platform apps like SubEthaEdit and Gobby which run on OSX and Linux respectively.&lt;/li&gt;
&lt;/ol&gt;&lt;p&gt;About the only drawback to pair programming with VNC is that there can be some fairly significant lag (between 1-4 seconds) depending on network load on either end, but even so, when it comes to &lt;em&gt;actually&lt;/em&gt; developing collaboratively, VNC and Skype are our daily tools of choice.&lt;/p&gt;&lt;h3&gt;VNC Clients/servers&lt;/h3&gt;&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;OSX client&lt;/strong&gt;: &lt;a href='http://sourceforge.net/projects/cotvnc/' title='Chicken of the VNC'&gt;Chicken of the VNC&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;OSX server&lt;/strong&gt;: &lt;a href='http://www.redstonesoftware.com/products/vine/server/vineosx/' title='Vine Server'&gt;Vine Server&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Windows/Linux client/server&lt;/strong&gt;: &lt;a href='http://www.tightvnc.com/download.html' title='Tight VNC'&gt;http://www.tightvnc.com/download.html&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;</content>



 </entry>
 
 <entry>
   <title>Taming The Rhino Making Mozillas Javascript Command Line A Little Less Brutish</title>
   <link href="/2006/08/04/taming-the-rhino-making-mozillas-javascript-command-line-a-little-less-brutish/"/>
   <updated>Liquid error: undefined method `xmlschema' for "Fri Aug 04 11:19:23 -0500 2006":String</updated>
   <id>/2006/08/04/taming-the-rhino-making-mozillas-javascript-command-line-a-little-less-brutish</id>
   <content type="html">&lt;p&gt;I recently &lt;a href='learning-javascript-from-the-command-line'&gt;described&lt;/a&gt; how to use the one of the &lt;a href='http://www.mozilla.org/js/'&gt;freely available shells&lt;/a&gt; as a great way to explore your javascript runtime. There are two implementations of the javascript interpreter sponsored by the Mozilla project, &lt;a href='http://www.mozilla.org/js/spidermonkey'&gt;Spider Monkey&lt;/a&gt; an interpreter implemented in C, and &lt;a href='http://www.mozilla.org/rhino/'&gt;Rhino&lt;/a&gt;, an interpreter implemented in Java. With respect to the javascript runtime itself, these two implementations are almost identical, and so what works in one, will generally work in the other. They diverge, however, when it comes to embedding objects and functions that are implemented in a language other than javascript. Naturally, Spidermonkey is better suited for embedding objects implemented in C, while Rhino excels at embedding objects implemented in Java.&lt;/p&gt;&lt;p&gt;What exactly is &quot;embedding&quot; an object implemented in Java? If you don't know what this means already, I could try to describe it to you, but why not show it live and in the flesh with the Rhino command line? That's the exploratory technique that I find so valuable.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;cowboyd@subzero:~$ java -classpath js.jar org.mozilla.javascript.tools.shell.Main 
Rhino 1.5 release 5 2004 03 25
js&amp;gt; var javaString = new java.lang.String(&amp;quot;Hello World&amp;quot;)
js&amp;gt; javaString.hashCode()
-862545276
js&amp;gt; javaString.startsWith(&amp;quot;Hello&amp;quot;)
true
js&amp;gt; javaString.startsWith(&amp;quot;World&amp;quot;)
false
js&amp;gt; var jsString = new String(&amp;quot;Hello World&amp;quot;)
js&amp;gt; jsString.startsWith(&amp;quot;Hello&amp;quot;)
js: &amp;quot;&amp;lt;stdin&amp;gt;&amp;quot;, line 5: uncaught JavaScript exception: TypeError: startsWith is not a function. (&amp;lt;stdin&amp;gt;; line 5)
js&amp;gt;                    &lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;As you can see, javaString is a reference to an actual &lt;code&gt;java.lang.String&lt;/code&gt; object, and has access to all the methods of that class, many of which are not contained in the native javascript &lt;code&gt;String&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Embedding goes two ways. Not only can you instantiate and use java objects from javascript, but you can also pass in javascript objects as parameters to java methods. You can even extend objects and implement interfaces in javascript! Once again, the command line shows this in action. In this example, we&amp;#8217;ll implement the &lt;code&gt;java.lang.Runnable&lt;/code&gt; interface in javascript&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;cowboyd@subzero:~$ java -classpath js.jar org.mozilla.javascript.tools.shell.Main 
Rhino 1.5 release 5 2004 03 25
js&amp;gt; var impl = new Object()
js&amp;gt; impl.run = function() {print(&amp;quot;Yeah that&amp;#39;s right, you better run!&amp;quot;)}

function () {
    print(&amp;quot;Yeah that&amp;#39;s right, you better run!&amp;quot;);
}

js&amp;gt; var runnable = new java.lang.Runnable(impl)
js&amp;gt; var thread = new java.lang.Thread(runnable)
js&amp;gt; thread.run()
Yeah that&amp;#39;s right, you better run!
js&amp;gt;                                          &lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This is all well and good, but that's quite a bit of code to get right the first time! Chances are, if you're just starting out with the Rhino command line, you're not going to have as much luck, especially if you're using it as a tool to learn javascript in the first place, and unfortunately, this is where Rhino comes up &lt;em&gt;way&lt;/em&gt; short. Rather than have a forgiving &lt;a href='http://en.wikipedia.org/wiki/Command_line_interface'&gt;CLI&lt;/a&gt;, Rhino punishes you for every syntactic and semantic error that you make by not collecting command history. Even worse, hitting the up and down arrows result in bizarre character literals output directly to the prompt. You can't even correct a mistake that you've made in the current line you're typing without backspacing all the way to the error, and then re-typing from that point on.&lt;/p&gt;&lt;p&gt;In this example, I'd like to arrow-left so that I can correct my misspelling of &quot;java.lang&quot;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;cowboyd@subzero:~$ java -classpath js.jar org.mozilla.javascript.tools.shell.Main 
Rhino 1.5 release 5 2004 03 25
js&amp;gt; var r = new java.lng.Runnable(^[[D^[[D^[[D^[[D&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;Ugh!&lt;/strong&gt; Or what happens if the shell didn't take my last command because it was slightly bogus? I'd like to retrieve the command with the up-arrow, edit it a little bit in-place and then try again because after all, it was only &lt;em&gt;slightly&lt;/em&gt; bogus. Watch me try and recover from this minor syntax error...&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;cowboyd@subzero:~$ java -classpath /usr/share/java/js.jar org.mozilla.javascript.tools.shell.Main
Rhino 1.5 release 5 2004 03 25
js&amp;gt; var f = function() {print(&amp;quot;oops I forgot to close these parens&amp;quot;}
js: &amp;quot;&amp;lt;stdin&amp;gt;&amp;quot;, line 29: missing ) after argument list
js: var f = function() {print(&amp;quot;oops I forgot to close these parens&amp;quot;}
js: ...............................................................^
js: &amp;quot;&amp;lt;stdin&amp;gt;&amp;quot;, line 29: missing } after function body
js: var f = function() {print(&amp;quot;oops I forgot to close these parens&amp;quot;}
js: ...............................................................^
js: &amp;quot;&amp;lt;stdin&amp;gt;&amp;quot;, line 29: Compilation produced 2 syntax errors.
js&amp;gt;
js&amp;gt; //I know. Up-arrow to the rescue!
js&amp;gt; ^[[A^[[A^[[A^[[A^[[A^[[A //drat, foiled again! &lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;These problems are in particularly nasty contraposition to the technique of exploration via the shell which I advocate because the the cost for failure is so expensive. Indeed, what is so wonderful about most modern shells is that the cost for a syntax error is so small. For some reason, the implementors of the Rhino CLI decided to implement their shell with the typical functionality circa 1962.&lt;/p&gt;&lt;p&gt;It's not a problem for me though, thanks to one of my favorite unsung java libraries, &lt;a href='http://jline.sourceforge.net/'&gt;JLine&lt;/a&gt;. JLine hits a super sweet spot in that it takes somewhere around 0 effort to add loads of standard functionality to your command line interfaces. It seems that no one in the java world bothers with a decent CLI; tragic in my opinion, but probably because it's considered well-understood, non-trivial and therefore tedious. With JLine, building that CLI comes at around 0 cost. What's really cool about JLine is that a program doesn't even need to be written with it. It can transparently intercept the console input for &lt;em&gt;any&lt;/em&gt; java program and seamlessly splice on any and all functionality you'd expect from a hot shell: in-place editing, command history, you name it. In a word: &lt;em&gt;perfect&lt;/em&gt; for a beast like Rhino.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;cowboyd@subzero:~$ java -classpath js.jar:jline.jar  jline.ConsoleRunner org.mozilla.javascript.tools.shell.Main
Rhino 1.5 release 5 2004 03 25
js&amp;gt; prnt(&amp;quot;oops let me try that again&amp;quot;)
js: &amp;quot;&amp;lt;stdin&amp;gt;&amp;quot;, line 1: uncaught JavaScript exception: ReferenceError: &amp;quot;prnt&amp;quot; is not defined. (&amp;lt;stdin&amp;gt;; line 1)
js&amp;gt; print(&amp;quot;oops let me try that again&amp;quot;)
oops let me try that again
js&amp;gt; //trust me, that was easy. Just like it should have been in the first place.
js&amp;gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;JLine truly is a healing salve for your chafing CLI woes. Did I mention that it's cross-platform?&lt;/p&gt;&lt;p&gt;While the barrier to entry is extremely low, the path to upgrade is but a mild upward slope. If you do end up wanting nice extras such as TAB-completion or custom key bindings, it has a simple configuration mechanism, and &lt;a href='http://jline.sourceforge.net/apidocs/index.html'&gt;Java API&lt;/a&gt; to make the pain of writing custom code as minimal as possible. But that's another bedtime story altogether.&lt;/p&gt;&lt;p&gt;I hope you enjoy JLine with Rhino, or with any other impolite java command lines you may use!&lt;/p&gt;</content>



 </entry>
 
 <entry>
   <title>Learning Javascript From The Command Line</title>
   <link href="/2006/08/02/learning-javascript-from-the-command-line/"/>
   <updated>Liquid error: undefined method `xmlschema' for "Wed Aug 02 11:49:36 -0500 2006":String</updated>
   <id>/2006/08/02/learning-javascript-from-the-command-line</id>
   <content type="html">&lt;p&gt;In the &lt;a href='http://www.drunkandretired/podcast'&gt;Drunk and Retired Podcast&lt;/a&gt;, &lt;a href='http://www.drunkandretired.com/2006/07/08/drunkandretiredcom-podcast-episode-59-lightside-v-darkside-plus-learning-javascript-the-language-not-the-javascript-the-browser-scriptus/#comments'&gt;episode  59&lt;/a&gt; I spoke about learning your way around javascript the language independently from the browser, and how you can use the command line tools that come with the various javascript engines to interactively explore the javascript runtime.&lt;/p&gt;&lt;p&gt;When most folks think about javascript, they think about scripts that they embed into their web pages, but the truth is that it is a general-purpose programming language &lt;em&gt;that has absolutely nothing to do with HTML&lt;/em&gt;. In fact, the javascript runtime is so orthogonal to other web browser functionality, that mozilla offers the javascript interpreter that it uses in Firefox and friends as a &lt;a href='http://www.mozilla.org/js/spidermonkey'&gt;completely separate download&lt;/a&gt;. It's available as both .deb or .rpm package, and just to show it: Here's the wonderful hello world program, as entered into the shell.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;cowboyd@subzero:~$ js
js&amp;gt; alert(&amp;#39;hello world&amp;#39;)
1: ReferenceError: alert is not defined
js&amp;gt;    &lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;OK, so I boobie-trapped that example in an attempt to beat the point I've been making to death. It's an error because `alert()` isn't actually part of javascript. In the context with which we're familiar(DHTML), it's a function that's &lt;em&gt;defined by the browser&lt;/em&gt;. Of course, it just so happens that every browser implements `alert()` to behave in almost exactly the same way, but the function itself has nothing to do with the javascript core. Implementing our own version of alert is simple enough though.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;js&amp;gt; var alert = function(message) { print(message)}
js&amp;gt; alert(&amp;#39;hello world&amp;#39;)
hello world
js&amp;gt;            &lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Personally, I love the command line because it let's you dig your fingers deep into the computer's brain and, by pushing its buttons directly, see what's going to work and what isn't. Every time I have a question about how the javascript interpreter is going to behave, I don't look up the spec, or write something into my programs that I'm not sure how it will work. Instead, I fire up my trusty interpreter to discover &lt;em&gt;empirically&lt;/em&gt; how the system works. Need to know if a RegExp is going to match? Don't guess. Ask the interpreter.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;js&amp;gt; &amp;quot;foo&amp;quot;.match(/bar/)
null
js&amp;gt; &amp;quot;foo&amp;quot;.match(/oo/)
oo
js&amp;gt; &amp;quot;foo&amp;quot;.match(/oo$/)
oo
js&amp;gt;             &lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Wonder what the built-in &quot;constructor&quot; property of an object is? The runtime can tell you. It's his business after all.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;js&amp;gt; function A() {}
js&amp;gt; var a = new A()
js&amp;gt; var o = new Object()
js&amp;gt; a.constructor

function A() {
}

js&amp;gt; o.constructor

function Object() {
    [native code]
}

js&amp;gt; o.constructor == Object
true
js&amp;gt; a.constructor == A
true
js&amp;gt;                            &lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Sure, you could write an in-browser script to do all this and throw output at yourself in the form of alerts, but the beauty of the javascript command line is that you can collapse the whole edit-save-reload-alert scripting cycle into a single step; type in the next line and see what happens. It's that super-tight feedback which let's you learn that much faster.&lt;/p&gt;</content>



 </entry>
 
 <entry>
   <title>Live Stylesheets</title>
   <link href="/2006/07/15/live-stylesheets/"/>
   <updated>Liquid error: undefined method `xmlschema' for "Sat Jul 15 20:41:42 -0500 2006":String</updated>
   <id>/2006/07/15/live-stylesheets</id>
   <content type="html">&lt;p&gt;Even after working with DTML for over a year, I'm still constantly astounded by how &lt;em&gt;dynamic it actually is&lt;/em&gt;. The most important thing to keep in the back of your head as a DHTML programmer is that the same mechanisms used by the browser to build an HTML document at load time are available to your in-page scripts. So, really, the static loading of your pages when you access a url is just the HTML parser invoking the same methods on the same objects that are available to your javascript code.&lt;/p&gt;&lt;!--break--&gt;&lt;p&gt;Take this static HTML code:&lt;/p&gt;&lt;code type='html'&gt;
&lt;html&gt;
&lt;body&gt;&lt;div id='foo'&gt;This is my div&lt;/div&gt;&lt;/body&gt;
&lt;/html&gt;
&lt;/code&gt;&lt;p&gt;The same result can be achieved dynamically:&lt;/p&gt;&lt;code type='html'&gt;
&lt;html&gt;
&lt;body onload='addFoo()'&gt;
&lt;script type='text/javascript'&gt;
function addFoo() {
   var foo = document.createElement('div')
   foo.id = &quot;foo&quot;
   var fooContent = document.createTextNode(&quot;This is my div&quot;)
   foo.appendChild(fooContent)
   document.body.appendChild(foo)
}   
&lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;
&lt;/code&gt;&lt;p&gt;Nothing mind-blowing there; indeed, this technique is the cornerstone of DHTML. But it takes awhile to let it sink in to the point where using it is one of your first strategies to solving a problem. Specifically, you can use it not only to dynamically change layout-related HTML elements (span, div, ul, table, et al...), but also to create/modify &lt;em&gt;behavioral elements&lt;/em&gt;(link, script, meta, etc...)&lt;/p&gt;&lt;p&gt;That said, I was recently trying to create a CSS stylesheet at runtime, and enable it so that its rules would be active in the page. At first, I was trying to use the &lt;a href='http://www.w3.org/TR/DOM-Level-2-Style/ecma-script-binding.html'&gt;W3C DOM CSS interface&lt;/a&gt;, the idea being to  create a stylesheet object, add a bunch of rules to it corresponding to the rules that I wanted, and then put it into the stylesheets array. Unfortunately, doing this in a cross-platform way is &lt;a href='http://www.quirksmode.org/dom/w3c_css.html'&gt;borderline impossible&lt;/a&gt;. After pounding my head against that for awhile and getting nowhere,  I figured, &quot;why not just create the whole thing as a top-level html element, and let the browser just take it away from there?&quot; The basic strategy is this: create a &lt;code&gt;style&lt;/code&gt; DOM Element dynamically, add text content to it representing the actual stylesheet, and then pop it into the HTML DOM. With a few caveats, it works like a charm. The browser parses the text as CSS, and links in into the live cascade.&lt;/p&gt;&lt;p&gt;I mentioned caveats.. well, of course there are the obligatory cross-browser compatibility issues to be aware of:&lt;/p&gt;&lt;ul&gt;
  &lt;li&gt;In Internet Explorer, you can't just append a Text Node to a Style element, you have to use some trickery to get it to work.&lt;/li&gt;
  &lt;li&gt;KHTML &amp;amp; Safari do not honor &lt;code&gt;style&lt;/code&gt; elements that are not contained in the HEAD element of the document.&lt;/li&gt;
  &lt;li&gt;While IE and Mozilla always create a HEAD element for you if one doesn't exist, Opera and KHTML do not.&lt;/li&gt;
  &lt;li&gt;While Opera will honor a dynamically created HEAD element, KHTML will not. (That's a bug in KHTML as far as I'm concerned as it violates the DHTML principle that I've been talking about.)&lt;/li&gt;
&lt;/ul&gt;&lt;p&gt;All in all, they're nothing to worry about and do not stand in the way of the fundamental technique. I've created a &lt;a href='/bitbucket/live-stylesheet.html'&gt;demo page&lt;/a&gt; showing this code in action. As a nice side effect, it works as quick way of playing around with CSS properties and how they effect the styling of elements.&lt;/p&gt;&lt;p&gt;Here is the source snippet implementing the technique I've described here:&lt;/p&gt;&lt;code type='javascript'&gt;
   var style = document.createElement('style')
   style.setAttribute('type', 'text/css')

   var cssText = $('cssText').value
   if (style.styleSheet) { //IE only
      style.styleSheet.cssText = cssText
   } else {
      //for some reason this fails in IE.
      var text = document.createTextNode(cssText)
      style.appendChild(text)
   }
&lt;/code&gt;</content>



 </entry>
 
 
</feed>
