I was asked recently (well sort of) to give an example of saving an image to the server. If you look at teethgrinder's example for this, you will see that he has made available an external interface to do just that - POST your graph as png raw data to your server for storage. This has many benefits such as saving the image for use in a PDF report or for printing, since we know at times it is a bit troublesome to print the embedded flash object.
I think the main problem people are having with this is the receiving of the image data post - see the upload_image method below. Also, teethgrinder's example never really says where to make the post_image() call. So I touch on both in the code below.
Here is an example of the png that is saved when I did this for the chart in the previous example:
Well, let's just get right in to the code.
The controller contains the same code as my last post with only a few minor changes to the index method and the addition of the upload_image method.
In the controller, I have this:
12345678910111213141516171819202122
classTestItController < ApplicationControllerdefindex# note the user of open_flash_chart_object_from_hash instead of just open_flash_chart_object# this allows you to pass in the id of the div you want the the chart to be in# this is useful for when we need to findSWF by this id@graph = open_flash_chart_object_from_hash("/test_it/chart", :div_name => "my_chart")end# added to recieve the post data for the OFC png image of the OFC graphdefupload_image name = "tmp_image.png" || params[:name]# the save_image method that is provided by the OFC swf file sends raw post data, so get to it like this data = request.raw_postFile.open("#{RAILS_ROOT}/tmp/#{name}", "wb") { |f| f.write(data) } if data render :nothing => trueenddefchart# same code from here - http://pullmonkey.com/2010/01/05/open-flash-chart-ii-x-axis-date-and-time/ ...endend
So just note the use of open_flash_chart_object_from_hash() in the index method, this way we can pass in the id of the div.
Really the only difference from what we would normally have in our view is that I am using the save image setup method that was added to the open flash chart ruby on rails plugin in the last couple hours (as of this post). The save_image method takes some arguments, mainly the url to post the image data to and the id of the chart we setup in the controller.
It is something we sort of dreamed up and it works great as a partial CMS - very much like SimpleCMS where you can specify what exactly on the page needs to be managed by a CMS. This allows you to mix your CMS static content with your dynamic content.
Been having problems with swap space and memory on my slicehost servers. And it is all apache's and mongrel's fault. That used to be the cool combination and now it is an ugly, sluggish beast. Just recently, I switched to nginx (to replace apache) and thin (to replace mongrel). So far so good, major speed improvements and definitely memory consumption improvements.
I started out by switching everything over the nginx while keeping the mongrels alive, that was actually pretty easy. Information was available everywhere.
Thinning everything via capistrano took a while, that wasn't as well documented. Thin was documented, capistrano was documented, but easy solutions as to how to combine the two were difficult to find.
Here's the solution I was able to come up with -
Capistrano
My config for using mongrel used to look something like this -
set :stages, %w(staging production)
set :default_stage, "production"
set :application, "myapplication.com"
set :user, "appuser"set :repository, "http://svn.myapplication.com/myapp/trunk"
set :deploy_to, "/var/www/#{application}"
role :app, application
role :web, application
role :db, application, :primary=>true
set :runner, user
set :keep_releases, 3
set(:mongrel_conf){"#{current_path}/config/mongrel_cluster.yml"}
deploy.task:after_update_code, :roles=>[:web]do
desc "Copying the right mongrel cluster config for the current stage environment."
run "cp -f #{release_path}/config/mongrel_#{stage}.yml #{release_path}/config/mongrel_cluster.yml" end
... <other things like symlinks>
Now that we are moving from mongrel to thin, no need for two lines in particular, one being the line that requires mongrel_cluster recipes and the other that sets the mongrel_cluster yaml config path. A third line changes from mongrel_cluster.yml to thin_cluster.yml. You get something like this:
set :stages, %w(staging production)
set :default_stage, "production"
require"capistrano/ext/multistage"
set :application, "myapplication.com"
set :user, "appuser"
set :repository, "http://svn.myapplication.com/myapp/trunk"
set :deploy_to, "/var/www/#{application}"
role :app, application
role :web, application
role :db, application, :primary=>true
set :runner, user
set :keep_releases, 3
deploy.task:after_update_code, :roles=>[:web]do
desc "Copying the right mongrel cluster config for the current stage environment."
run "cp -f #{release_path}/config/thin_#{stage}.yml #{release_path}/config/thin_cluster.yml" end
... <other things like symlinks>
Now we need to implement what mongrel recipes was doing for us, start, stop and restart but in terms of thin (added this to the bottom of my deploy.rb):
namespace :deploydo
desc "Restart the Thin processes on the app server."
task :restartdo
run "thin restart -C #{release_path}/config/thin_cluster.yml" end
desc "Start the Thin processes on the app server."
task :startdo
run "thin start -C #{release_path}/config/thin_cluster.yml" end
desc "Stop the Thin processes on the app server."
task :stopdo
run "thin stop -C #{release_path}/config/thin_cluster.yml" end end
Just as an attention grabber - we are going after this example in this article:
Keeping up
Ok, seeing that the php versions of open flash chart and open flash chart swf files continually change along with with the API (not saying this is a bad thing), I wanted to come up with an even more abstract solution. The goal is to not have to worry when the swf file is released with the latest set of graphs or changes its API. I simply don't want to worry about this method or that method, or this class or that class.
Feedback
This article will sort of act as a tutorial for those interested in metaprogramming and as a set of instructions for those looking to experiment with the latest version of the OFC II Rails Plugin that I am currently toying with. I would like to hear feedback, but just remember that phase 1 of this release will be very basic, meaning none of the ajaxy stuff. It will come, just not yet.
Let's see what we can get away with
I am already using method_missing() for pretty much everything in the OFC II Rails Plugin that is being used now. But every time new classes are added, I have to sit down and basically convert the php class to ruby - just plain tedious, not really what I had planned when I started all this. Ok, so method_missing() was great, but let me introduce (or possibly reintroduce) you to const_missing(), basically method_missing() but instead of methods, we can create classes or modules or other objects on the fly. This will definitely help when the php version gets a new class. Instead of getting hounded to update the rails version to be 100% like the php version, everything will just work, no updates to code required. Well, we hope ! So check this out:
Here is what we did with method_missing():
1234567891011121314151617181920212223
moduleOFCclassBasedefmethod_missing(method_name, *args, &blk)case method_name.to_swhen/(.*)=/# i.e., if it is something x_legend=# if the user wants to set an instance variable then let them# the other args (args[0]) are ignored since it is a set methodself.instance_variable_set("@#{$1}", args[0])when/^set_(.*)/# backwards compatible ... the user can still use the same set_y_legend methods if they wantself.instance_variable_set("@#{$1}", args[0])elseif inst = self.instance_variable_get("@#{method_name}") instelse# if the method/attribute is missing and it is not a set method then hmmmm better let the user knowsuperendendendendend
This just basically allows me to do this:
12345678910111213
classFoo < OFC::Baseend foo = Foo.new foo.some_random_attribute = "Hello"#=> "Hello" foo.some_random_attribute #=> "Hello" foo.some_random_undefined_attribute #=> Method Missing error (calls super)# too be like php, for easier conversion foo.set_some_random_attribute("Good Bye") #=> "Good Bye" foo.some_random_attribute #=> "Good Bye"
Along the same lines, I have created an initialize method that takes any argument hash of variable/value pairs and calls variable=() which is handled by method missing as we saw above:
Ok, so on to const_missing() and what we can do with that:
123456
defOFC.const_missing(const) klass = Class.new OFC::BaseObject.const_set const, klassreturn klassend
This says that any undefined (missing) constant of OFC should be defined as a new class that inherits from OFC::Base.
So when we say OFC::Foo, that has not been defined, so we will get back class OFC::Foo < OFC::Base;end; which will give us the initialize() method and method_missing() method from above. Let's see how this works:
So it all sort of came together right there. I've shown you all the code that comes with the Rails Open Flash Chart plugin now. No more definining idividual classes, no more trying to keep up with the never ending php version, and no more late nights converting php to ruby (!). About dang time.
Ok, but this is just the beginning, nothing has been set in stone, so like I said, give me your feedback, what works for you and what does not. And, hopefully, I will have solutions for you or you for me.
Example with new version (test version)
I am using rails 2.3.2, but I don't think it will matter what version you are using.
Create your new rails project
12345
# create a new rails project > pullmonkey$ rails testing_it#<Bunch of stuff is created ....>> pullmonkey$ cd testing_it/
Install the plugin from the test branch
Note the -r test in this next step. The new version (test version) I am playing with is under the test branch and -r says what branch to pull from.
Also, you can use git:// instead of http:// below, but depending on your firewall restrictions http:// will probably work out best for you.
> pullmonkey$ ./script/generate controller test_it# <And more stuff >
Get our assets
1234567
# first we will get swfobject.js> pullmonkey$ cp vendor/plugins/open_flash_chart/assets/javascripts/swfobject.js public/javascripts/# next the open flash chart swf (GET whatever is the latest version), right now that is here: http://teethgrinder.co.uk/open-flash-chart-2/open-flash-chart.swf> pullmonkey$ cd public/> pullmonkey$ wget http://teethgrinder.co.uk/open-flash-chart-2/open-flash-chart.swf> pullmonkey$ cd ..
Edit our controller
Notice here that I just include one of the many examples from the plugin's examples directory. Definitely more to follow.
One thing you will notice about the examples, is that the php code is in the comments, so you can see how I would convert from the php examples to ruby. Please feel free to add your own examples, just fork the project.
12345678910
> pullmonkey$ vi app/controllers/test_it_controller.rb# mine looks like this:classTestItController < ApplicationController include OFC::Examples::AreaHollowdefindex@graph = open_flash_chart_object(600,300, "/test_it/area_hollow")endend
Edit our view
12345
> pullmonkey$ vi app/views/test_it/index.html.erb# mine looks like this:<%= javascript_include_tag 'swfobject'%><%= @graph %>
Start 'er up
12345
> pullmonkey$ ./script/server# browse to the test_it indexhttp://localhost:3000/test_it
I've been using the spreadsheet gem lately for a couple projects I am working on to modify existing spreadsheets. I have quite often stumbled upon this error when opening modified spreadsheets in excel:
File error: data may have been lost
Like most microsoft errors, it was useless and the spreadsheet came up just fine. But that error was just so annoying, other spreadsheet applications (open office, excel on mac) opened without any problems. So after quite a bit of hacking and digging around, I finally tried setting the encoding, which defaults to UTF-8. Well it just so happens that the spreadsheet being modified was encoded with UTF-16LE.
So part one of my solution became this:
12
Spreadsheet.client_encoding = 'UTF-16LE'
Then doing a little more digging I decided that this would be a better long-term solution:
123
book = Spreadsheet.open spreadsheet_fileSpreadsheet.client_encoding = book.encoding
Well, hopefully it wasn't just me and someone will be able to save a bit of time with this.
Got an email today, I have seen it before and I am sure it has been going around for years. This time, I thought that I would do an exercise and create a plugin that duplicates what I found in this email. See for yourself.
Here is the email I got:
What I gathered was that the only important letters are the first and last letter of each word, those have to be in the right order. So the rest of the letters can be in any random order. That is what I did - I created a plugin and put it out on github. You can install it like this:
Update: Bloggity does not require the Engines plugin to run if you are using Rails 2.3 or above (where the Engines plugin is baked in). -- Noted below by Bill.
Update: Added the plugin to github - simple_blog. It is not production ready or really all that usable quite yet.
Ok, so this a rant and I am sorry for that - but as simple as it is, I have been looking for a blog plugin lately. The problem with the plugins I find is that I don't want to have to deal with the engines plugin or have the controllers, models, views, etc ... all extracted into my applications code. I want it all external (hence a plugin) but let it be minimally configurable.
So in my recent search for a blog plugin for rails, I came across two that look very useful, but each with their flaws:
1) bloget - Everything is extracted to my code space. Why? Yes, I realize that it is most likely because I will want to override things, but get out of my space and keep to yourself!
Provide me a way to override things that I would need to (there really shouldn't be too many), after all it is ruby.
2) bloggity - Uses the engines plugin! I have nothing against the engines plugin (I think it is well written and documented) but for a freaking blog plugin?!? Why?
Is there a third option?
Glad you asked - yes, there is a third option - I hate to say it, but do it right! There's your third option.
Ok, but really, if there is a third option (a third plugin), I would love to hear about it.
Ok, so all that to lead up to a little plugin tutorial? Well, it got your attention didn't it?
Starting from scratch
Ok, I guess I will start from scratch. So let's get started.
You should see the post we created up above via Post.create(...) and its associated comment that we also created above.
Note:Feel free to overwrite any of the views. This can be done simply for the posts index view by creating the same file under RAILS_ROOT/app/views/posts/index.html.erb and doing what you'd like.
That's it for part 1
Ok, so that's part 1. The goal was to keep everything external and I think we succeeded (aside from migrations).
No offense to those that use engines or extract files into one's application's space, we all have our ways - the above is what I prefer.
Part 2 will consist mainly of filling this out a bit more and further discussion on adding helpers, routes and migrations to your plugin without interfering in the application's code space.
Building on line graph clicking, thanks to the support of a few other people (mentioned throughout the article) we now have bar graph clicking as well. The only down side (if you want to call it that) is that it is experimental in the sense that the open flash chart swf object had to be updated, and the update is not part of the official OFC release (at least not at the time of this writing). No big deal though, just be aware. It is however part of the OFC rails plugin release.
Big thanks goes to Eric for his work on the action script for the bar clicking open-flash-chart swf file - see this forum entry for more details.
Pull the latest from github and make sure to get Eric's swf file (under the assets directory - open-flash-chart-bar-clicking.swf ) and place it under RAILS_ROOT/public
The call to open_flash_chart_object() has changed to accept an optional parameter for the swf file name. I am leaving the original for use as open-flash-chart.swf (which is the default for the swf_file_name param) and added Eric's as open-flash-chart-bar-clicking.swf. See the example below for usage.
classTestItController < ApplicationControllerdefindex@graph = open_flash_chart_object(600,300,"/test_it/graph_code", true, "/", "open-flash-chart-bar-clicking.swf")enddefgraph_code title = Title.new("Bar on-click Example") bar = BarGlass.new# NOTE ... the next two lines are if you want each bar to have a different response when clicked bar_values = (1..9).to_a.map{|x| bv = BarValue.new(x); bv.on_click = "alert('hello, my value is #{x}')"; bv} bar.set_values(bar_values)# if you want a more generic response across all bars, then the following lines would do:# bar.on_click = "alert('hello there')"# bar.set_values((1..9).to_a) chart = OpenFlashChart.new chart.set_title(title) chart.add_element(bar) render :text => chart.to_sendend