Monday, April 21, 2008

Ruby on Rails Best Practices

I have worked with ruby on rails framework 1 year, and my friend and I find some ways that might be best practices in this framework.

1. If your logic code that interacts with database is complicated, you should make it as a class method so that this method could be reusable by other developers in the team. You can return true/false to indicate this process is successful or failed if you don't want any validation errors object. You can also return object/an array of object to get validation errors.

2. Don't use render :update do |page|....end which is the bad thing because it returns a javascript code to the browser. And don't use link_to_remote :update => "id" because this code also generates javascript code back to the browser. Instead, use render :partial => 'update' to render the plain html code back to the browser and use oncomplete callback to replace the old content with the new result such as: document.getElementById('id').innerHTML = request.responseText;

Friday, April 18, 2008

Dynamically loading external javascript files and css files

As web applications are getting larger and more complex than before, they include many javascript files and css files on head section of the html. Web developers need to make their application load faster as possible. There are 2 ways that can make the web page load faster than before:
1. Load only the very basic script files on the head section. Other external files should be at the end of the body section of the html. Then on the onload event, you can use function or component in those external scripts as normal. It works better than including them on the head of section because the browser load them at the end. This make the user sees browser displaying some information rather than blank pages.
2. Some other people call the second ways "Just-in-time". When the page is loading, they load those external script. When the user interact with web page, they load them immediately.
http://www.felocity.org/blog/article/just_in_time_loader_for_javascript/
These below links talk about this issues, but these scripts don't know when the loading is finished. The way they use is create a script tag, set src to file from their web server, and last append it the head.
http://www.javascriptkit.com/javatutors/loadjavascriptcss.shtml
http://www.javascriptkit.com/javatutors/loadjavascriptcss2.shtml
You can create a timer to detect whether it complete by checking objects in the window object, (eg. window['Draggable']). Or, you can add onload event handler to script tag.
http://cain.supersized.org/archives/2-Dynamic-loading-of-external-JavaScript-.js-files.html
But other people use ajax to load it and then eval it from request.responseText.
http://www.web2coder.com/website-design/dynamically-loading-external-javascript-file-3
http://cain.supersized.org/archives/2-Dynamic-loading-of-external-JavaScript-.js-files.html

Subscribe in a Reader