Harry Seldon's blog

Fractals, Chaos, and Control Systems on Rails

Read

Stacked bar chart with Rails and Open Flash Chart

Posted by Harry Seldon on April 20, 2009

Consequently to questions about the stacked bar charts, I have added an example to the OFC test app. Once again this example is a translation of the original example from Teethgrinder. However, this time there are indeed a few catches.

See the live example of the stacked bar chart here

The code
in test_it_controller.rb:

  def index_stacked_bar
    @graph = open_flash_chart_object(600,300,"/test_it/graph_code_stacked_bar")     
  end

  def graph_code_stacked_bar
    title = Title.new("A stacked bar chart")
    title.set_style( "{font-size: 20px; color: #F24062; text-align: center;}" );
    bar_stack = BarStack.new

    # set_colours does not work
    # set a cycle of 3 colours:
#    colour_array =  Array.new( [ '#C4D318', '#50284A', '#7D7B6A'] )# yellow purple gray
##    bar_stack.set_colour('#C4D318', '#50284A', '#7D7B6A');
#    bar_stack.set_colour(colour_array);
#    # add 3 bars:
#    bar_stack.append_stack( Array.new( [2.5, 5, 2.5 ]) ); # 0
#    # add 4 bars, the fourth will be the same colour as the first:
#    bar_stack.append_stack( Array.new( [2.5, 5, 1.25, 1.25 ]) ); # 1 
##    debugger
#    bsv4 = BarStackValue.new(5, '#ff0000') #red
#    bsv5 = BarStackValue.new(2, '#ff00ff') # 3 pink
#   
#    bar_stack.append_stack( Array.new( [5,bsv4] ) ); # 2 red 
#    bar_stack.append_stack( Array.new( [2, 2, 2, 2,  bsv5]) ); # 3 pink 

    # Using  BarStackValue to set the colour     
    bsv1 = BarStackValue.new(2.5, '#C4D318') # yellow    
    bsv2 = BarStackValue.new(5, '#50284A')   # purple
    bsv3 = BarStackValue.new(1.25, '#7D7B6A') # gray
    bsv31 = BarStackValue.new(1.25, '#C4D318') # yellow
    bsv4 = BarStackValue.new(5, '#C4D318') # yellow
    bsv41 = BarStackValue.new(5, '#ff0000') # red
    bsv5 = BarStackValue.new(2, '#ff00ff') # pink    
    bsv6 = BarStackValue.new(2, '#C4D318') # yellow
    bsv7 = BarStackValue.new(2, '#50284A') # yellow
    bsv8 = BarStackValue.new(2, '#7D7B6A')   # purple

    bar_stack.append_stack( Array.new( [bsv1, bsv2, bsv1 ]) ); # 0
    bar_stack.append_stack( Array.new( [bsv1, bsv2, bsv3,bsv31 ]) ); # 0
    bar_stack.append_stack( Array.new( [bsv4,bsv41] ) ); # 2 red 
    bar_stack.append_stack( Array.new( [bsv6, bsv7, bsv8, bsv6,  bsv5]) ); # 3 pink 

#   Does not work    
#    bsk1 = BarStackKey.new( '#C4D318', 'Kiting', 13 )
#    bsk2 = BarStackKey.new( '#50284A', 'Work', 13 )
#    bsk3 = BarStackKey.new( '#7D7B6A', 'Drinking', 13 )
#    bsk4 = BarStackKey.new( '#ff0000', 'XXX', 13 )
#    bsk5 = BarStackKey.new( '#ff00ff', 'What rhymes with purple? Nurple?', 13 )
#    
#    bar_stack.set_keys(Array.new([bsk1, bsk2,bsk3,bsk4,bsk5]))
##    bar_stack.set_keys(Array.new([bsk1, bsk2,bsk3,bsk4,bsk5]))
    bar_stack.set_tooltip( 'X label [#x_label#], Value [#val#]<br>Total [#total#]' );

    y = YAxis.new();
    y.set_range( 0, 14, 2 );

    x = XAxis.new();
    x.set_labels_from_array( Array.new( ['Winter', 'Spring', 'Summer', 'Autmn' ]) );

    tooltip = Tooltip.new;
    tooltip.set_hover();

    chart = OpenFlashChart.new
    chart.set_title(title)
    chart.add_element(bar_stack)

    chart.x_axis =  x ;
    chart.y_axis =  y ;
    chart.set_tooltip( tooltip );

    render :text => chart.to_s   
    end
 

in index_stacked_bar.html.erb:

<script type="text/javascript" src="/javascripts/swfobject.js"></script>
<%= @graph %>

The catches
In Teethgrinder’s code there is a call to the set_colours method. For some undetermined reasons this method does not work with OFC. Instead we directly set the color using the color parameter in BarStackValue. However, the BarStackValue class constructor returned me an error about a bad number of arguments. So I needed to make the following modification:
in vendor/plugins/open_flash_chart/lib/open_flash_chart/bar_stack.rb

  
  class BarStackValue < Base
    def initialize(val,colour, args={})
      super args
      @val    = val
      @colour = colour     
    end
  end

Moreover the BarStackKey function that allows to write the legends is not implemented yet. This is something to be fixed in a future release.

A Reminder
For this example most of the code is in the controller. However, I remind you that the proper place for it would be in your model if you want to keep your code DRY.
You would use a graph like a view. Let us check this example:
In the model MyModel:

  
def make_chart_1
    title = Title.new("MY TITLE")
    bar = BarGlass.new
    bar.set_values([1,2,3,4,5,6,7,8,9])
    @chart = OpenFlashChart.new
    @chart.set_title(title)
    @chart.add_element(bar)
end

Notice you can add all the inputs you want to the graph creating function in the model.

In the controller:

  
  mymodel.make_chart_1

In the view :

 <%= mymodel.chart.js_open_flash_chart_object("my_chart_js_1", 550,300) %>

See this post for more info.

Enjoy your stacked bar chart. And by the way if you own a website using OFC leave a link so we can see it at work.

Posted in | 2 comments | Tags , , , , , | atom

Open Flash Charts examples with Rails

Posted by Harry Seldon on March 09, 2009

Posted in | no comments | Tags , , , , | atom

Use OFC in your model

Posted by Harry Seldon on December 19, 2008

I am only now upgrading my OFC plugin version in my Thinkosphere project. Last update was before all the refactoring made by dfl.
From this refactoring until now, you need to add the line ‘include OpenFlashChart’ in your model to properly use OFC. You do not need to do that in your controllers because OFC is already required for all controllers and views thanks to the following lines in init.rb:

require 'open_flash_chart'
ActionView::Base.send :include, OpenFlashChart::View
OpenFlashChart::Base.send :include, OpenFlashChart::View
ActionController::Base.send :include, OpenFlashChart::Controller
ActionController::Base.send :include, OpenFlashChart

So if you want to use OFC in your model (what you should want) simply add the following lines in init.rb:

ActiveRecord::Base.send :include, OpenFlashChart::View
ActiveRecord::Base.send :include, OpenFlashChart::Controller
ActiveRecord::Base.send :include, OpenFlashChart

Notice that this will work for your ActiveRecord model not the others.

Then why would you want to use OFC in your model ? Probably because you want to use a “fat model, skinny controller” policy. Doing so will allow you to easily reuse your code needed to prepare the graphs. If you have lots of graphs in your application that will be very efficient.

This code update is currently available on my github fork.
Update: It is now available on OFC home.

This makes me think that a small demonstration of use of OFC with models seems needed in the OFC test app. If someone feels like wanting to do it, do not hesitate ! I am specifically aiming at Anthony Navarre who left a nice code snippet as a comment on Charlie’s blog ;-)

Posted in | no comments | Tags , , , , | atom

News from Open Flash Chart

Posted by Harry Seldon on December 18, 2008

In November, Open Flash Chart was updated with some new features and bugfixes. OFC rails plugin was also updated thanks to Charlie, Zuk and Otavio. I have just updated the OFC test app. The list of changes brought by OFC new version is given at the end of this post.

Moreover, some new examples of OFC use are available around:

For reference, here is the list of changes of the latest OFC version:

Posted in | 1 comment | Tags , , , , | atom

Grand Gardening with GIT

Posted by Harry Seldon on November 08, 2008

Why is GIT so interesting ?

With git, I have been doing some gardening these days. Indeed I growed trees, cut branches, grafted branches.
I have been using a Version Control System (VCS) only for one year. That is about since I started the Thinkosphere project. I have been using SVN. At first I was like “Hey this is so cool”. SVN is a real time machine or at least a past time machine. You can easily go back in time to get the state of your source code from months ago. Unfortunately you cannot go forward to the future (with GIT you will be somehow able to do that !).

So after the honeymoon with svn, I began to find some limitations. Mainly I was missing an easy way to have two repositories talking to each other. Let’s see why. Here is a concrete example of how a Distributed Version Control System (DVCS) can be useful. This blog is powered by Typo which is open source. I downloaded the source code and I put it into a repository of mine to be able to make some minor changes (for instance these ones). But doing this I lost the connection with the original repo. That means I cannot easily upload my changes to the “main” repo neither can I go forward in time by downloading the last changes on the main repo.
This is exactly the kind of situation which git was designed for. Indeed with git the various repos can easily communicate with each other. So I can merge the latest updates from the main repo to my own local repo.

Tutorial

Let us see the setup of such a configuration in details. I will not use the example of this blog because it is still theoretical as I have not migrated it to git yet. Instead, I will use the exact configuration I am using to contribute to Open Flash Chart plugin and its test app.
Notice the setup is well explained in the excellent GIT User’s Manual at this chapter from which I am taking the following graph:

                      you push
your personal repo ------------------> your public repo
      ^                                     |
      |                                     |
      | you pull                            | they pull
      |                                     |
      |                                     |
      |               they push             V
their public repo <------------------- their repo

Let us go over the steps. Imagine you want to download OFC test app, you want to make your own modifications while being able to regularly download the updates and you also want to upload your changes.
For the configuration resulting from the following tutorial, I can precise this:

  • your personal repo = local repo = repo on your computer = repo in your working copy
  • your public repo = repo on github, mine is here
  • their repo = repo on PullMonkey’s computer
  • their public repo = ‘official’ repo = repo on PullMonkey’s github

Let me precise also some GIT Vocabulary :

  • To upload your changes from a repo to a repo is to push.
  • To download your changes to a repo from a repo is to pull (to be precise pull fetches the changes and merge them to the current branch).
  • To upload your changes from your working copy (or working tree) to your repo is to commit.
  • To download changes from your repo to your working copy is to checkout (checkout command is also a simple command to switch between branches).
  • Downloading a repo to create a repo : clone.

First, your fork the public repo to a public repo of yours: You go there you click on fork. (you will need a github account)
Then you download (clone) your repo to your local repo :

git clone git://github.com/pullmonkey/ofc_test_app.git

(It both creates the repo and checks it out)

Now you make some changes. You commit them:

git commit -a -m "my changes"

You want to upload your changes to your public repo:

git push

You want them to take into account your changes. You send them a pull request through email or github.
They agree to try it, they pull from your repo to their repo. They love it. They push it to their public repo.

They also made some more changes. You want to get them.
The first time you need to add the address of the public repo:

git remote add their_public_repo git@github.com:pullmonkey/ofc_test_app.git

Then, here is the GIT’s beauty, you pushed to a repo but you pull from another repo:

git pull their_public_repo

You can add as many repos as you want. You can see all these repos from a part of the global tree of the application development. Each repo is a tree branch. More than that each repo can contain several branches. Each branch can have a purpose: development, test, release etc. So have a happy gardening and happy time travels with git !

Any mistake, any problem or everything works ? Leave a comment !

Git resources:

Bonus

As I am a private pilot, all this push/pull stuff made me think about the push/pull aircraft :

Notice it has two propellers aligned with the fuselage one to pull and one to push.

Posted in | 8 comments | Tags , , , , , | atom

A test and example app for Open Flash Chart Rails plugin

Posted by Harry Seldon on November 07, 2008

On October 24th, David Lowenfels aka dfl added the beginning of a test app in OFC plugin. As I had myself a local test app used to play around with OFC I thought it would be nice to add my test code in the OFC plugin. This code is actually made mainly by Charlie’s examples taken from his blog and my own examples.

A test app would be useful for 2 main reasons. The first one, as it says, is for testing purposes. The recent changes brought to OFC plugin were great but they were lacking some tests (functional tests and backward compatibility tests). So more tests are definitely necessary. The other reason which is almost more important is the need for working examples. The examples exist on Charlie’s blog and they are very helpful. As they exist why not gather them in an example app ? The examples will be yet more useful and clear.

So first, I worked directly on the app put by dfl in the test directory. But quickly I found it weird to have an application inside a plugin and using this plugin with the application inside etc. You get the kind of recursive situation (not as bad as it seems though!). So I proposed to Charlie to simply make a side test app. For now, the app is here in my repo on github but as it is more natural to put it close to the OFC plugin, Charlie will fork it and the “official” repo will be on his github repo probably here [EDIT: this is done].

[EDIT] If you also have your own OFC test app, and you want to contribute, have a look at this post explaining how to do it with GIT.

Taken from the README :
Both a testing and tutorial application for Rails Open Flash Chart Plugin.
Version 0.2.0
1) Install with:

git clone git://github.com/harryseldon/ofc_test_app.git    

EDIT PullMonkey’s version not up to date.

git clone git://github.com/pullmonkey/ofc_test_app.git    

2) Run your server:

script/server -p 3000   

3) Go to http://localhost:3000/test_it/all_graphs
You will see all the graphs, like here.

EDIT 3/9/2009 This app is running live here.

All your comments on how to test a Rails plugin are welcome.

Posted in | no comments | Tags , , , , , | atom

Radar chart example with OFC2

Posted by Harry Seldon on October 23, 2008

Following up from yesterday’s example of a scatter line chart. Here is an example of a radar chart. The purpose is double. the first one is to test OFC2 plugin update (let’s say it now: it works !), the second one is to make an example. As Charlie pointed it out, I am leaving the php code to show that if you need further information on OFC2 rails plugin API you actually only need to go to OFC’s original website. For instance, the code from this example is taken here. Notice there are 2 other examples of radar charts here. Let me know in the comments if you have translated to Ruby one of them.

Here is the controller (test_it_controller.rb).

class TestItController < ApplicationController
  def index_radar
    @graph = open_flash_chart_object(600,300,"/test_it/graph_code_radar")
  end

  def graph_code_radar
    # based on this example - http://teethgrinder.co.uk/open-flash-chart-2/radar-chart-lines.php
#    $chart = new open_flash_chart();
     chart = OpenFlashChart.new
#    $chart->set_title( new title( 'Radar Chart' ) );
     chart.set_title(Title.new('Radar Chart'))
#    $line_1 = new line_hollow();
     line_1 = LineHollow.new
#    $line_1->set_values(array(3, 4, 5, 4, 3, 3, 2.5));
     line_1.set_values(Array.new([3, 4, 5, 4, 3, 3, 2.5]))
#    $line_1->set_halo_size( 2 );
     line_1.set_halo_size( 2 )
#    $line_1->set_width( 1 );
     line_1.set_width( 1 )
#    $line_1->set_dot_size( 3 );
     line_1.set_dot_size( 3 )
#    $line_1->set_colour( '#FBB829' );
     line_1.set_colour( '#FBB829' )
#    $line_1->set_tooltip( "Gold<br>#val#" );
     line_1.set_tooltip( "Gold<br>#val#" )
#    $line_1->set_key( 'Mr Gold', 10 );
     line_1.set_key( 'Mr Gold', 10 )

#    $line_2 = new line_dot();
     line_2 = LineDot.new
#    $line_2->set_values(array(2, 2, 2, 2, 2, 2, 2));
     line_2.set_values(Array.new([2, 2, 2, 2, 2, 2, 2]));
#    $line_2->set_halo_size( 2 );
     line_2.set_halo_size( 2 )
#    $line_2->set_width( 1 );
     line_2.set_width( 1 )
#    $line_2->set_dot_size( 3 );
     line_2.set_dot_size( 3 )
#    $line_2->set_colour( '#8000FF' );
     line_2.set_colour( '#8000FF' )
#    $line_2->set_tooltip( "Purple<br>#val#" );
     line_2.set_tooltip( "Purple<br>#val#" )
#    $line_2->set_key( 'Mr Purple', 10 );
     line_2.set_key( 'Mr Purple', 10 )
#    $line_2->loop();
     line_2.loop() # to close the loop

#// add the area object to the chart:
#    $chart->add_element( $line_1 );
     chart.add_element( line_1 )
#    $chart->add_element( $line_2 );
     chart.add_element( line_2 )
#    
#    $r = new radar_axis( 5 );
     r = RadarAxis.new( 5 )

#    $r->set_colour( '#DAD5E0' );
     r.set_colour( '#DAD5E0' )
#    $r->set_grid_colour( '#DAD5E0' );
     r.set_grid_colour( '#DAD5E0' )
#    $labels = new radar_axis_labels( array('Zero','','','Middle','','High') );
     labels = RadarAxisLabels.new(Array.new(['Zero','','','Middle','','High']))
#    $labels->set_colour( '#9F819F' );
     labels.set_colour( '#9F819F' )
#    $r->set_labels( $labels );
     r.set_labels( labels );

#    $spoke_labels = new radar_spoke_labels(array(
#        'Strength',
#        'Smarts',
#        'Sweet<br>Tooth',
#        'Armour',
#        'Max Hit Points',
#        '???',
#        'Looks Like a Monkey') );
    spoke_labels = RadarSpokeLabels.new(Array.new([
        'Strength',
        'Smarts',
        'Sweet<br>Tooth',
        'Armour',
        'Max Hit Points',
        '???',
        'Looks Like a Monkey']))

#    $spoke_labels->set_colour( '#9F819F' );
     spoke_labels.set_colour( '#9F819F' )
#    $r->set_spoke_labels( $spoke_labels );
     r.set_spoke_labels( spoke_labels )
#    $chart->set_radar_axis( $r );
     chart.set_radar_axis( r )
#    $tooltip = new tooltip();
     tooltip = Tooltip.new()
#    $tooltip->set_proximity();
     tooltip.set_proximity()
#    $chart->set_tooltip( $tooltip );
     chart.set_tooltip( tooltip )
#    $chart->set_bg_colour( '#ffffff' );
     chart.set_bg_colour( '#ffffff' )
#    echo $chart->toPrettyString();
    render :text => chart.to_s
  end
end

The view code is as simple as usual (index_radar.hml.erb):

<script type="text/javascript" src="/javascripts/swfobject.js"></script>
<%= @graph %>

You can check out here the graph that has been made.

Thanks John and thanks Charlie.
H

Posted in | 11 comments | Tags , , , | atom

Scatter line chart example with OFC2

Posted by Harry Seldon on October 22, 2008

Yesterday, I needed a scatter line chart for my project. I saw that my current version of OFC did not do it. However, I saw that a new version that has the feature had come out : OFC version 2 Gamera. Looking at pullmonkey’s blog, there was nothing new so I was afraid the update was not made yet. Another look, this time directly on github and good news Charlie had updated OFC2 plugin. To be precise, last commit says “open flash chart gamera not tested yet, but available for those that want to try it out”. So let’s try out the part that interests me: the scatter line chart. I am directly translating this example from Teethgrinder just like I had done for another OFC example.

For simplicity sake, I do not use the ajax way to draw the chart. Notice also that if you adhere to the skinny controller fat model policy, the graph_code function should be in your model. Before using the following code, you need to install the edge version of OFC2 plugin (script/plugin install git://github.com/pullmonkey/open_flash_chart.git –force). Do not forget to update public/open-flash-chart.swf and public/javascripts/swfobject.js.

Then, here is the controller (test_it_controller.rb). You still have the original php code (and I still hate the $ sign before every variable).

class TestItController < ApplicationController
  def index_scatterline
    @graph = open_flash_chart_object(600,300,"/test_it/graph_code_scatterline")
  end

  def graph_code_scatterline
    # based on this example - http://teethgrinder.co.uk/open-flash-chart-2/scatter-line-chart.php
    #$chart = new open_flash_chart();
    chart =OpenFlashChart.new
    #$title = new title( date("D M d Y") );
    title = Title.new(Date.today.to_s)
    #$chart->set_title( $title );
    chart.set_title(title)
    #$s = new scatter_line( '#FFD600', 3 );
    scatter_line = ScatterLine.new( '#FFD600', 3 )
    #$v = array();
    v = Array.new
    #$x = 0.0;
    x = 0
    #$y = 0;
    y = 0
    #do
    while x < 25 
      #  $v[] = new scatter_value( $x, $y );
      v.push(ScatterValue.new(x,y))
      #    // move up or down in Y axis:
      #    $y += rand(-20, 20)/10;
      y += (-1+2*rand)*2
      #    if( $y > 10 )
      #        $y = 10;
      if y>10
        y=10
      end
      #    if( $y < -10 )
      #        $y = -10;
      if y<-10
        y=-10
      end
      #    $x += rand(5, 15)/10;
      x += (5+10*rand)/10
      #while( $x < 25 );
    end
    #$s->set_values( $v );
    scatter_line.set_values(v)
    #$chart->add_element( $s );
    chart.add_element(scatter_line)
    #$x = new x_axis();
    x_axis = XAxis.new
    #$x->set_range( 0, 25 );
    x_axis.set_range(0,25)
    #$chart->set_x_axis( $x );
    chart.x_axis = x_axis
    #$y = new x_axis();
    y_axis = YAxis.new
    #$y->set_range( -10, 10 );
    y_axis.set_range( -10, 10 )
    #$chart->add_y_axis( $y );
    chart.y_axis = y_axis
    #echo $chart->toPrettyString();
    render :text => chart.to_s
  end
end

The view code is as simple as usual (index_scatterline.hml.erb):

<script type="text/javascript" src="/javascripts/swfobject.js"></script>
<%= @graph %>

You can check out here the graph that is made. The graph is randomly generated so if you refresh it, it is normal that it changes. As a bonus you notice this graph looks like a stock market chart (hum is stock market random? I will need another post to explain that. Until then use your common sense).

Thanks John and thanks Charlie.
H

Posted in | 8 comments | Tags , , , , | atom

Tutorial Rails/OFC/Ajax : Alter the chart using Javascript

Posted by Harry Seldon on September 28, 2008

In a first example I showed how to load a chart using javascript. Here I will show you how to dynamically alter an OFC chart without recreating it. This example is a raw adaptation of this Teethgrinder’s example. The chart is hard coded in ajax code so it is not loaded by OFC rails plugin, this will be done in a next example. Indeed, the aim of all this is at some point to be able to create a chart and then modify it to hide one signal or to zoom in or to change the legend, or etc.

The controller code is simple. Well OK it is even void (as I said the graph is hard coded in the javascript, it gives you opportunity to see how an OFC graph is serialized in json):

class TestItController < ApplicationController
def index_js_4
end
end

Everything happens in the view (index_js_4.html.erb) through ajax code and OFC code. I assume you have installed OFC rails plugin. You need 2 more things: the json2 library available here and the ajax code from Teethgrinder available here. Put these 2 js files in your public/javascripts folder.

The view:

<html>
    <head>
        <%#= javascript_include_tag :defaults, 'swfobject' %>
        <script type="text/javascript" src="/javascripts/swfobject.js">
        </script>
        <script type="text/javascript" src="/javascripts/json2.js">
        </script>
        <script type="text/javascript" src="/javascripts/tutorial-js.js">
        </script>
        <script type="text/javascript">

            function ofc_ready(){
                alert('ofc_ready');
            }

            function open_flash_chart_data(){
                // alert( 'reading data' );
                return JSON.stringify(data);
            }

            function findSWF(movieName){
                if (navigator.appName.indexOf("Microsoft") != -1) {
                    return window[movieName];
                }
                else {
                    return document[movieName];
                }
            }

            var data = {
                "elements": [{
                    "type": "hbar",
                    "values": [{
                        "left": 0,
                        "right": 5
                    }, {
                        "left": 0,
                        "right": 3
                    }, {
                        "left": 4,
                        "right": 8
                    }, {
                        "left": 4,
                        "right": 8
                    }, {
                        "left": 4,
                        "right": 8
                    }],
                    "colour": "#AF99DF"
                }],
                "title": {
                    "text": "Sat Sep 27 2008"
                },
                "y_axis": {
                    "labels": ["Job 1", "Job 2", "Job 3", "Job 4", "Job 5"]
                },
                "x_axis": {
                    "offset": false,
                    "min": 0,
                    "max": 10
                }
            };
        </script>
        <script type="text/javascript">
            swfobject.embedSWF("/open-flash-chart.swf", "my_chart", "550", "350", "9.0.0");
        </script>
    </head>
    <body>
    Here is the chart:
    </p>
    <div id="my_chart"></div>
    <p>
        <a href="javascript:update(data)">Update</a>, <a href="javascript:save(data)">Save</a>
    </p>
    <br/><br/>
    </body>
</html>

To understand this example have a look at the js file tutorial-js.js. It contains the update and save functions. It is understandable even by someone like me who does not speak javascript fluently. You can see the live example here.

Posted in | no comments | Tags , , , , , , | atom

A Rails/OFC/Ajax raw example

Posted by Harry Seldon on September 27, 2008

Here is a simple exercise to use Rails, OFC, OFC rails plugin and ajax together. The idea is just to follow the example given here in php. At first I did not manage to get this working. That is why I asked some help to Pullmonkey. He did a great job to make this working in this nice post . Moreover, he came up with nice improvements on OFC to render a chart using ajax and using Rails helper to keep a pretty code (you need to update OFC plugin to make his example work). However I want to show you here the translation in Rails of Teethgrinder’s tutorial with minimum code (no need to update OFC plugin).

Controller code (test_it_controller.rb), notice it has the original php code from teethgrinder in it.

class TestItController < ApplicationController
def tuto_5
    title = Title.new("tuto_5")
    #$title = new title( date("D M d Y") );
    #$chart = new open_flash_chart();
    @chart = OpenFlashChart.new
    #$bar = new bar();
    bar = BarGlass.new
    #$bar->set_values( array(9,8,7,6,5,4,3,2,1) );
    bar.set_values([1,2,3,4,5,6,7,8,9])
    #$chart->set_title( $title );
    @chart.set_title(title)
    #$chart->add_element( $bar );
    @chart.add_element(bar)
end
end

Then I had directly coded the view code (tuto5.html.erb) without helpers (and quite ugly) :

<head>
<script type="text/javascript" src="/javascripts/json2.js"></script>
<script type="text/javascript" src="/javascripts/swfobject.js"></script>
</head>

<body>
<script type="text/javascript">
swfobject.embedSWF("/open-flash-chart.swf", "my_chart", "350", "200", "9.0.0");
</script>
<script type="text/javascript">

function ofc_ready()
{
    alert('ofc_ready');
}

function open_flash_chart_data()
{
    alert( 'reading data' );
    return JSON.stringify(data);
}

function findSWF(movieName) {
  if (navigator.appName.indexOf("Microsoft")!= -1) {
    return window[movieName];
  } else {
    return document[movieName];
  }
}

var data = <%= @chart.to_s %>;
</script>

<p>Hello World</p>
<div id="my_chart"></div>
</body>

In this example you need the json2.js library that you can find here. However notice that Pullmonkey uses directly the json capabilities of Rails which is a much better way.
This code works, you can check it out here.

Thanks to Pullmonkey ! H

Posted in | no comments | Tags , , , , | atom

Search

Navigate


Recent Comments

Recent Posts

Tags

actuators aircraft atc blog chaos chaos_theory charts control controllers controls crisis economy finance flight fractals git gnc gs guidance linux mandelbrot marketing navigation ns ofc on pilot rails ruby sas scs sensors statistics systems techcrunch thinkosphere tutorial typo ubuntu wifi

Categories

Archives

Syndicate


Sponsor