There were quite a few changes that were required to get it working with rails 2.1, so they are in the repository now.
So to install, you pretty much follow the same instructions from before.
The only thing I have not completely resolved is the use of the simple_cms_item partial that sits in the plugin's app/views/shared directory. I tried forever to use append_view_path to share the partial over. That worked, as in it found the partial, but the application layout went away, so instead, you can just copy the partial to your RAILS_ROOT/app/views/shared directory for now.
Additionally, you can install it through github: script/plugin install git://github.com/pullmonkey/simple_cms.git
And of course, a lot of you have asked how to just plain download it, well you can do that here, find the download button and click :)
Ok, already, I heard ya :) The open flash chart (version 2 - OFC2) plugin is done (really just started) and it is out on github.
I rewrote the open flash chart plugin (started from scratch) to work with json like teethgrinder does here.
This time I think it is much slicker and a lot easier to work with.
I haven't tried much more than bar graphs, all the functionality is there for other types of graphs, just not tested.
So it is out there, and if you are willing to try it out, here is how:
Found a need for this information while answering questions on railsforum.
So, let's say that we want to use two databases and let's even say that we want to use an Oracle database and a MySQL database. How can this be done? To start, we must decide which database will be our default database. In this scenario, I chose MySQL. Let's see what that looks like:
1234567
# in your database.yml filedevelopment: adapter: mysql username: root password: database: example_development
So we have all seen that before. Now all of our active record models will use this mysql connection.
But, I need to use data from an oracle database, so let's setup that connection:
12345678910111213
# in your database.yml filedevelopment: adapter: mysql username: root password: database: example_developmentoracle_development: adapter: oracle username: root password: database: example_oracle_development
Neat, we have two development connections. Now we have to tell which models to use which connection. Well, actually, we just need to tell the oracle models to connect to oracle_development, all the other models will default to development. I have a model named user, and it's records are kept in an oracle database. Our user model looks like this initially:
Ok, great news. I have fixed a fairly large bug, Even better news, you probably never noticed it unless you were trying to output graphs via javascript, I.e., using graph.set_output_type("js").
Thanks go to Brandon, who provided an example of using javascript as the output type:
View Source Code
So if this was affecting you, then you will want to get the latest version of the plugin - Instructions.
After my last article about intersection and arrays, I got to thinking how this could apply elsewhere.
I decided to see if I could write a faster include?() method for Array using the intersection operator. So here is what I did:
1) Tested via irb (of course)
1234567891011121314151617181920
[pullmonkey]$ irb# build the array for conceptual testingirb(main):003:0> a = [1,2,3]=> [1, 2, 3]# see how include?() does itirb(main):004:0> a.include?(2)=> trueirb(main):005:0> a.include?(4)=> false# see what could be done with intersectirb(main):006:0> a & [2]=> [2]irb(main):007:0> (a & [2]).empty?=> false# this should return true, so negate itirb(main):008:0> !(a & [2]).empty?=> trueirb(main):009:0> !(a & [4]).empty?=> false
2) Extended the Array class with the faster_include?() method:
3) Wrote a performance test comparing elapsed time for true and false results:
12345678910111213141516171819
# size of the arrayx = 4000000# build the arraya = (1..x).to_ap "Finding #{x/2} ..."t1 = Time.nowp "include?() - returns true: #{a.include?(x/2)}"t2 = Time.nowp "faster_include?() - returns true: #{a.faster_include?(x/2)}"t3 = Time.nowp "include?() - returns false: #{a.include?(-50)}"t4 = Time.nowp "faster_include?() - returns false: #{a.faster_include?(-50)}"t5 = Time.nowp "Elapsed time for include?() returning true: #{t2 - t1}."p "Elapsed time for faster_include?() returning true: #{t3 - t2}."p "Elapsed time for include?() returning false: #{t4 - t3}."p "Elapsed time for faster_include?() returning false: #{t5 - t4}."
4) Just to see if there was a difference I got results and here they are:
Attempt 1:
12345678910
"Finding 2000000 ...""include?() - returns true: true""faster_include?() - returns true: true""include?() - returns false: false""faster_include?() - returns false: false""Elapsed time for include?() returning true: 0.308243.""Elapsed time for faster_include?() returning true: 0.271465.""Elapsed time for include?() returning false: 0.629375.""Elapsed time for faster_include?() returning false: 0.242673."
Attempt 2:
12345678910
"Finding 2000000 ...""include?() - returns true: true""faster_include?() - returns true: true""include?() - returns false: false""faster_include?() - returns false: false""Elapsed time for include?() returning true: 0.323652.""Elapsed time for faster_include?() returning true: 0.272212.""Elapsed time for include?() returning false: 0.594751.""Elapsed time for faster_include?() returning false: 0.277882."
Note that faster_include?() is consistent in elapsed time for a result of true and a result of false. However, include?() takes much longer in both attempts to return false than it does to return true, well actually about twice as long. include?() goes through each element, and I am using the midway point of the array in all tests, so it makes sense that include?() would return true in half the time it would take to return false. Very interesting, so now that I see performance improvement with faster_include?(), I need to do a wider spread of tests and for more attempts:
Note that arrays with 50 items or less seem to perform better using include?(), but barely. On the other hand with an array of 5M items, you shave off half a second using faster_include?().
So there you have it, faster_include?() can keep its name :)
Have you ever needed to retrieve the intersection of arrays in an array. Well, I did.
Let's say that you have a has and belongs to many (habtm) association between articles and tags, (I.e., a tag habtm articles and an article habtm tags). This means that tag.articles will return a list of articles that have that tag and article.tags will return the tags of the article. So if a user wants to search your blog for all articles that have 'tag1' and 'tag2', you would return all common articles.
Picture a search page with a list of check boxes, one for each tag that you have. The user can click as many tags as they want and then it is your job to find the common articles between them. The search POST contains the ids of the selected tags, like params[:tag_ids] = ["1", "3", "15"] or something. Let's go with this example.
1) The first step is to find those tags:
1
>> tags = Tag.find(params[:tag_ids])
2) Next, we want to get the articles associated with each tag, we will work with the ids:
I have seen this asked a lot in the forums, so I thought I would write up a little tutorial.
For this tutorial I am going to have three select boxes. The first select box will be a super category of the next two select boxes and the second select box will be a super category of the third select box. I hope that makes sense. To demonstrate, I thought I would use Genre -> Artist -> Song. So let's get started:
Create your models and build your migrations:
1234
ruby script/generate model genre name:stringruby script/generate model artist name:string genre_id:integerruby script/generate model song title:string artist_id:integer
Populate your genres, artists and songs through a migration:
Yes, I know it is generic data, sorry. So anyway, as you can see there are 3 genres, each with 2 artists, for a total of 6 artists each with 2 songs for a total of 12 songs. Each genre has 4 songs through its artists. Ok, so now we need to populate the database:
12
rake db:migrate
Now we need to modify our models to set up the associations.
Looks like it works :) Ok, now on to the controller. Our controller needs to have some action for the view, I just used index, and two other actions, for remote function calls, I called these update_artists and update_songs. update_artists() is called when a genre is changed and it updates the list of artists and the list of songs based on the genre. update_songs() only updates the songs based on the artist. So let's look at this code:
# the controller
classTestItController < ApplicationControllerdefindex@genres = Genre.find(:all)@artists = Artist.find(:all)@songs = Song.find(:all)enddefupdate_artists# updates artists and songs based on genre selected genre = Genre.find(params[:genre_id]) artists = genre.artists songs = genre.songs render :updatedo |page| page.replace_html 'artists', :partial => 'artists', :object => artists page.replace_html 'songs', :partial => 'songs', :object => songsendenddefupdate_songs# updates songs based on artist selected artist = Artist.find(params[:artist_id]) songs = artist.songs render :updatedo |page| page.replace_html 'songs', :partial => 'songs', :object => songsendendend
Now as far as views go we have one view (index.html.erb) and two partials (_songs and _artists). Let's take a look at those:
# the _songs partial (_songs.html.erb):
We are continuously adding to and changing the Simple CMS Plugin so here is a little rundown of what has been changed so far:
Major Changes:
I have updated to rails 2.0.2 so if you are using an older version you will need to change a line in each of the controllers.
123456
# Where it has:self.view_paths << File.join(File.dirname(__FILE__), '..', 'views')# Must be Changed to:self.template_root = File.join(File.dirname(__FILE__), '..', 'views')
The acts_as_versioned plugin is now required for the revisions. I added this quite some time ago. I did change the rake task to install this plugin as well as the rest.
You now have to pass a :prefix if you have one. This is to ensure that all content such as images, media, smiles, etc. work correctly. If your base path is a standard path then you do not need to worry about this.
For example: I was running 3 rails applications under one domain so it looked like this:
my.domain.com
/blog
/forum
/demo
So I would call my Simple CMS content like this for blog:
Now you can make content viewable and editable from multiple pages by passing :reusable => true. This defaults to false. Your label must be the same in each place you use it. This is very useful for layouts, such as header and footer.
*NOTE* If you already have content here and you change this variable you will lose all that content as it gives the content a new id and changes the params and how the content is called. For example if I have :reusable set to false and I have content there and I set :reusable to true then it creates content with a different id so I will not be able to use the old content until I change it back to false.
Minor Changes:
When you click on a revision you are taken back up to the top of the page instead of having to scroll all the way down a list of 100 revisions, clicking on one, and then manually scrolling all the way back up to the top to see if you even picked the right revision
I have added code highlighting and this requires the coderay plugin, which has been added to the rake simple_cms:install_dependencies, and a coderay stylesheet so you need to add that to your application layout. I have included it in the rake simple_cms:install
123
<%= stylesheet_link_tag "coderay"%>
I have also changed many things in the javascripts inside the tiny_mce editor so it would be safest just to use the rake tasks that are built in:
1234
rake simple_cms:uninstallrake simple_cms:install
I have updated the tutorial with all the changes as well.
There is also a demo that you can use to play around with it and ask questions.
Windows' servers are pretty much an awful nightmare to get working. A company that I am doing work for had the bright idea of hosting a fairly major web application on windows. Not a good idea, not a good idea at all. This has caused nothing but problems from ferret to having no way of stopping a service to this error - Errno::EINVAL - Invalid argument.
The typical error you get looks something like this:
Ya, that is not something you want to get and have no idea what is going on, not to mention that it only happens every once in a while. Especially, when you are already frustrated because nothing else seems to work perfectly.
The error is caused when you are using a windows server and have decided that, as a good windows' administrator, you will create a mongrel service for your application and set it to start automatically. The service knows nothing about STDOUT, so anything written to STDOUT will produce the error above. But, what still baffles me is the complete and utter randomness of the whole situation. Why does it not happen all the time, why only every 6 to 10 times that I hit the same exact page? Well, I can't help you there, but let me know if you have figured it out.
So, if you are lucky enough to get the same error above, then I have a solution for you, well actually a couple solutions. First, if you have the choice, ditch windows, not worth it. However, if you are like me and are forced to use windows for a project then your solution is a simple derivative of what you will find here.
None of those solutions worked for me, or at least not to the point where I was satisfied. They all got me very close, but without a way of still logging STDOUT. The closest and, as the link above points out, the safest was to redirect STDOUT to a logfile:
12
STDOUT.reopen(...)
Well, that, unfortunately, did not work for me for some reason, probably some fault of windows, I am sure. If you get it working, stick with that solution. Otherwise, I went with the following:
123456789101112131415161718
#################################### RAILS_ROOT/lib/std_out_logger###################################classStdOutLoggerdefwrite(s) f = File.open("log/stdout.log", "w+") f.puts s.inspect f.closeendend#################################### RAILS_ROOT/app/controllers/application.rb#################################### redirect the output to a log file for when we run as a servicebefore_filter {$stdout = $stderr = StdOutLogger.new}
I hope that helps you, it worked for me. Good luck.
I just finished converting version 1.9.7 of Open Flash Chart over to ruby, for use with rails.
Check out what I can do now :) I can customize my tooltips:
Well, we have been working on SimpleCMS a little and just for kicks we added revisions.
Check out the Simple CMS Plugin Demo
On this page you will see the "Show all revisions" link at the bottom of the "edit" page.
So feel free to add or delete or change revisions at will.
Also, if you are new to SimpleCMS, check out the sort of rough getting stared page.
Well, enjoy and please leave comments/feedback/requests here in the comments or preferably in the list of requests we have started on the demo page :)
A while ago, I was taking a look at a problem on the rails forum. This post was submitted to find the best solution to round any number to the nearest multiple of 10. For example, this method would take the number 6 and return 10, or the number 29 and return 30. So the first thing that popped into my mind was modulus. We can use modulus to determine how far we are from the nearest multiple of 10. Meaning that if we are given 19 and we want to know how close we are to the nearest 10, we can simple do 19 % 10, which will return 9, and 10 - 9 is 1, so we are 1 away from the nearest 10 spot. Here is that method, assuming only Fixnum, so it is implemented as an extension of the Fixnum class:
12345678
classFixnumdefroundupreturnselfifself % 10 == 0# already a factor of 10returnself + 10 - (self % 10) # go to nearest factor 10endend
While this did the job, it was suggested that it would be better if things happened.
Use the Numeric class (this class encompasses Float, Fixnum and Integer)
Don't limit the method to just the nearest 10, have it as a parameter
I first saw the need to convert a hash object to a class when answering this post.
In the post, the user wanted to load a YAML object into his hash and then present the data from the hash in a form. Needless to say it was not very DRY the way it had to be implemented. So I started looking into it, I found this. This solution was a great starting point for where I ended up, but it was not general enough, it was hard coded, plus it was missing the getters and setters. So it turns out that in ruby it wasn't too much trouble to convert a hash into a class object. So let's get started:
I have implemented this for use in Rails, so let's start with the model that does all the magic:
1234567891011
classHashitdefinitialize(hash) hash.each do |k,v|self.instance_variable_set("@#{k}", v) ## create and initialize an instance variable for this key/value pairself.class.send(:define_method, k, proc{self.instance_variable_get("@#{k}")}) ## create the getter that returns the instance variableself.class.send(:define_method, "#{k}=", proc{|v| self.instance_variable_set("@#{k}", v)}) ## create the setter that sets the instance variableendendend
Notice the self.class.send(:define_method ...) rather than self.define_method, this is a hack to overcome the fact that define_method() is private. I had come across this when trying to figure out the post mentioned above. Found the information to solve this here.
Ok, so on to the Controller that creates the Hashit object:
And of course, now the view, what we wanted to clean up and make more elegant. Here is what the user started with:
Note: In this example @hashit is an actual hash, not a class object.
Much simpler, DRYer :)
Well that is pretty much it, I suppose the next step would be to have a save method that updates the hash? This way we can do @hashit.save() and it will return a new hash that you can use. Well actually, that probably isn't too hard, lets see if I can do it real quick, class object back to hash ...
Well, I am back and I was able to figure it out, here is the new class:
12345678910111213141516171819
classHashitdefinitialize(hash) hash.each do |k,v|self.instance_variable_set("@#{k}", v)self.class.send(:define_method, k, proc{self.instance_variable_get("@#{k}")})self.class.send(:define_method, "#{k}=", proc{|v| self.instance_variable_set("@#{k}", v)})endenddefsave hash_to_return = {}self.instance_variables.each do |var| hash_to_return[var.gsub("@","")] = self.instance_variable_get(var)endreturn hash_to_returnendend
Just added the save() method, that takes all the instance variables and sets them as keys in our new hash. So here is the outcome of our save():
Neat, this is just from the examples, more to come with opengl when I get a chance.
Check out this guy's opengl stuff, really cool!
This requires java applet support, and I can say that it works wonderfully in Linux/FireFox, and Alias (from above) says that it works with IE. So there you have it.
I just finished converting the latest version of Open Flash Chart over to ruby, for use with rails.
Check out what I can do now :) Like the google analytics graphs.