Pass JavaScript variables to Rails controller 0

Posted by jay

Google query doesn’t give much useful result on this topic. What we discuss here is if there is a value/function getParameters() in JavaScript returns "message = hello_world" (a URL query). How do you pass the JS variable into controller?

link_to_remote

Most common way is using link_to_remote which constructs an Ajax call, but the drawback is you have to handle the params[:message] using RJS template (or please let me know if I was wrong). Here is the example:
<%= link_to_remote "Create Post", :url => {:controller=>'posts', :action =>'new'},  :method => :post, :with =>"getParameters();" %>

As you see, the :with option will eventually become :with => "message=hello_world". A new parameter is accessible by calling params[:message]. But what if I only want to render another page?

capture block

Capture block captures a variable for the view which can be reused. The idea is to call the JavaScript inside capture block to pass it as a Rails variable in view. The @param variable is readable in the view.
<% @param = capture do %>
<%= javascript_tag "document.write(getParameter());" %>
<% end %>

link_to_function

Remember that we have already passed the JavaScript value to @param variable, it is used here. An inline redirect_to does the trick, that redirects to the new action and value is accessible by calling params[:message].
<%= link_to_function "Create Post" do |page|
      page.redirect_to  "/posts/new" + "?" + @param
  end %>

I’m sure that you will have other ways of using these tricks in difference situation, but hope you get the idea and use them whenever is suitable.

Passing Rails restful_authentication in rspec 0

Posted by jay

Plugins in Rails are useful shortcuts, they produce better implementations for some areas. I recently come across an issue of passing model controller authentication, but the before_filter :login_required stops me testing my code in Rspec. By using mock and stub technique can pass the authentication test. All you have to do is inserting these code before your rspec test (or place it somewhere in helper class)
@current_user = mock_model(User, :id => 1)
controller.stub!(:login_required).and_return(:true)
controller.stub!(:current_user).and_return(@current_user)
This tells the test that :login_required always returns :true and the variable @current_user returns a mock model that is not nil.

Offline Rails Documentation 0

Posted by jay

Although you can run gem server to have a rails rdoc running on localhost, the rdoc rails document could be troublesome to find a specific method you would like to know about. Fortunately, you may want to try out an ajax improved rails documentation:
  • RailsBrain provides a free downloadable (free) offline documentation for rails. It has the lastest version 2.2.2 available for download. The ajax feature allows developer search method, class or file name via a input box. It’s a sufficient tool and I am using it now for development.
  • Gotapi is an online API collections. you can manage/view/search all the API you are currently using in any languages(e.g. PHP, Java, .net and of course rails). Similar features are privided as RailsBrains, but it’s only available online.
Updates on March 24 2009
  • Railsapi.com is a recent new project and is hosted on GitHub. It has better search capabilities. Intresting to note that it does not support Internet Explorer is currently (may be more specific version or not been IE tested). Apart from that, it’s smart, tidy and downloadable Rails doc.

Some Google's favicon.ico 0

Posted by jay

Back to June 2008 google’s Official blog published an article about icon changes. Although they are using only one official icon or logo, today I found a interesting thing when trying to spend some time tidy up my browser bookmark. some-google-icons

In my Google bookmark folder, I added Analytics, Adsense, AdWords and Google Reader. The screen shot attached may shown a few points:
  • Ah! Analytics has a nice graph favicon! Just like the one you seen in dashboard.
  • Adsense uses the same icon announced in their official blog
  • Strangely, Adwords still use the old icon
  • While google reader has no icon at all… oh no, I think they actually have one. It’s just my Firefox 3 doesn’t like to show it. After restart FF, reader icon showed!
This reminds me, I should place an favicon for my blog one day, when I have a monent.

Update: 11 Dec 2008:

I added a little favion for my web. For those who need to generate a nice smooth favicon using PhotoShop, I suggest to download a IcoFormat plugin from Telegraphics. The plugin is free and Easy to use. The CS3 version plugin is still workable on Adobe CS4.

Update: 19 Jan 2009

google-favicon-2009Everyone is looking for a new start for the year of 2009. It’s the year of the OX, yah! That means I’ve been through 2 twice 12-year cycle of animals. Google is always looking for fun and changes, hence they have updated fav icon again in the start of 2009.

I took a screenshot of my book mark which listed all the icons that Google have is using now. The Adsense icon is the one Google use for the home page. Other icons remain the same. Surprisingly, AdWords icon still have the good old classic favicon that have been used over a few years.

Stay toned. We may see more updates later .

"Fork Ruby" Summary (RubyConf 2008) 0

Posted by jay

I like screencast and keynote, they are great ways of learning practically. But some people don’t have much time to watch or listen to all these. Or maybe you forgot some ideas were presented, but it’s difficult to select the part you want to find in the video – you end up with watching the video again sometimes. So here I typed in a short summary of the keynote. If you are still interested, it’s worth to watching the video. And thanks to David Thomas giving this talk.

Presenter: David Thomas Background: Last RubyConf attended was in 2005, started working on Ruby back in 1999. He wrote books, talked at many events and went to a lot of conferences. HE recently went to many Rails conferences.

Why Fork Ruby

There are a lot of active project forking Ruby interpreter, e.g. JRuby, IronRuby, MacRuby, but they are not forking the Ruby language.

Problem with Release Time

1.0 -> 1.2 tookk 14 months -> 1.4 (8 months) -> 1.6 (13 months) -> 1.8 (48 months) -> 1.9 (54 months)
  • As you can see, bigger changes we make, the bigger challenges they are, more time required for next release.
  • The bigger changes make developer difficult to adopt to these new features.
  • Less people use the new release feature, release team will not be able to find problems.

Some (Potential) Projects Ideas

RubyLite

RubyLite is a light version of Ruby. The idea is that moving those listed less used features into Gem, developer install those gems only when they needed.
  • One of the things we can do with RubyLite is to lose some language features that we normally don’t use (e.g.):
    • %q delimiters
    • implicit string concatenation
    • alias
    • nested assignment
    • :: sign for method call
  • And other features we can get rid of: class variables, global variables, many combination of $ sign, unless/until, protected, proc
  • One encoding will make library much smaller, so how about support utf8.
  • Losing Built-in classes and modules: Complex, File::Stat, FileTest, Mutex, ObjectSpace, Process::Gid/Status/Sys/Uid, Rational, TreadGroup
  • Losing Built-in methods, a lot of methods are vibrations that produces the same result.

Parallel Ruby

Ruby already have the construction to produce parallelism: a, b = b, a

Ideally, Dave suggested that we could perform calculation using this parallel feature in separate threads or processes: a, b = calc1(x), calc2(y). He used some sample code of finding longest word in English, which demonstrated that a few lines code produced Map/Reduce.

Optionally-typed Ruby

Closure-based Ruby

This Is the Ruby with block, and it should be easy to create lambda. Suggestion is to remove {} sign for hash. Maybe we can express methods and classes in blocks.

Conclusion

There is nothing wrong with Ruby, “but that shouldn’t stop us from having fun”. The community should fork Ruby and experiment with it. If the result is positive, they will be put in main Ruby release. The Ruby release itself should not be part of the experiment.

IE6方程式: 提高开发效率 0

Posted by jay

Jeremy Keith在他的博客中写到关于如何选择对IE6支持的问题。对于不同的网站,他们有不同的用户群,如果很少部分的人用IE6,还要考虑对老版本的支持么?又如果在IE6中发现很小的错误,是否要修正,应该用多少工作时间?

Jeremy分析了不同层面极端的几个方案:
  • 将所有的 IE6 访问者踢出你的站点
  • 完全遵循标准开发,并且没有任何针对 IE6 的测试
  • 只使用 Dean Edwards 的脚本让 IE6 支持额外的 CSS
  • 编写针对 IE6 的样式解决大部分问题(比如布局等)
  • 让站点在 IE6 以及其他浏览器上看起来一摸一样
并和Cennydd Bowle一起推算出一个数学公式(使用 t 表示总的开发时间、t6 表示花在 IE6 上的时间;所有的访问者数目表示为 a、 a6 则表示正在使用 IE6 的访问者): p = 50 [ log ( at6 / ta6 ) + 1 ] 运算出来的p概率可以判断是应该应用 Dean Edwards 的 IE 脚本:
<!--[if lt IE 7]>
<script src="http://ie7-js.googlecode.com/svn/version/2.0(beta3)/IE7.js" type="text/javascript"></script>
<![endif]-->
<!--[if lt IE 8]>
<script src="http://ie7-js.googlecode.com/svn/version/2.0(beta3)/IE8.js" type="text/javascript"></script>
<![endif]-->
当然在某些极端的情况下,比如公司的政策内部一定要运用IE6,作为内部网络软件开发人员,应当要保证IE6的100%正常运作。在浏览器支持的问题上,Yahoo YUI发布过一篇很好的文章”Graded Browser Support”, 作为好的开发人员,这篇文章应该是必读的。

当然这些都不能解决本质问题,为软需要加大力度让客户门升级自己的IE。在2008年低,我们的AJAX技术不能单单的存活在1997年的浏览器技术上。

Computer Science Research Conference at Cambridge 0

Posted by jay

Have been waiting this day for several weeks now since I received invitation to Computer Sicence 2008 conference hold at Cambridge Homerton college.

To get UK research fund for international student become rather difficult. Unfortunatly, I’m in this hassle right now together with this economic down time.

So finally I’m off there for three days. Hoping to get some answers, ideas and help.

The conference was mainly about giving insite view of computer science research. For those who are looking for a reaseach career, we were taught a few tips. Some conference seminas are absolutly fabulars!

Why comics is important in research?

The seminar I enjoyed most was “The Power of Procrastination” given by Jorge Cham. He earned PhD in mechanical engineering from Stanford University and turned out to be a comic producer. He’s the creator of Piled Higher & Deeper (PHD Comics). The comics is based on some stories/conversation between gradudate students and PhD students. It makes people laugh in the case that some scene are happening in student life. Go to the PhD comics website, check out those archived comics.

Microsoft Research

One of the MS research branch is located in Cambridge, of course they presented and demoed some latest high tech(facial detection). They have more information on their Research website.

Google Research

This was a fun part. Actually, Google doesn’t have a specialised research branch, so, why they presented and sponsored the conference? One of the presenter, a Google engineer manager, said that their engineers do both engineering and research work at the same time. For example, their production server disk format is developed by their engineer to handle large a mount to search requests and caching, even operating system is speciallised designed for super large amount of requests. There is a wide list of unresolved issues to research on. So actually, even in this layoffs season(see yahoo action), it’s pretty amazing Google still have spares to hire more people, of course they have to be top notch.

Configure Rails migration version type 0

Posted by jay

Rails use a UTC time stamp as migration version by default. Although most examples in books have simple number based system for managing migration versions, there isn’t much information about version type configuration. By default, a migration file(>=Rail 2.0) name look similar to:
20081202130543_create_group_categories.rb
We can turn this off and use numeric prefixes by adding this in config/environment.rb
config.active_record.timestamped_migrations = false
New generated file name will look like:
003_create_group_categories.rb
But bare in mind, if the Rails project is getting large and a few developers are working on same project, it’s likely that two developers generate same version of migration (e.g. 003). Using time stamp is introduced since Rail 2.0 to avoid such problem. So… better keep the default setting!

config.gem 'rspec-rails' on Rails 2.2.2 0

Posted by jay

Update on 5th April 2009:

This rspec-rails gem issue has been fixed and released in rspec-rails milestone “1.2.0”. see details here

If you are still working on Rspec before version 1.20:

After googling, I counld’t find much information about including rspec-rails in the ruby gems config/environment.rb. The only reason I include it in gem dependency is for the sake of continuous integration, to make sure the build platform happy and green.

So, back to the topic. This was related to rspec bug #577 (still an open ticket), if placing the congif gem in this order:
config.gem 'rspec', :lib =&gt; "spec", :version =&gt; '1.1.11'
config.gem 'rspec-rails', :lib =&gt; "spec/rails", :version =&gt; '1.1.11'
you will likely to get errors:
/Library/Ruby/Gems/1.8/gems/rspec-1.1.9/lib/spec/runner/options.rb:229:in `files_to_load': File or directory not found: gems (RuntimeError)
    from /Library/Ruby/Gems/1.8/gems/rspec-1.1.9/lib/spec/runner/options.rb:221:in `each'
    from /Library/Ruby/Gems/1.8/gems/rspec-1.1.9/lib/spec/runner/options.rb:221:in `files_to_load'
    from /Library/Ruby/Gems/1.8/gems/rspec-1.1.9/lib/spec/runner/options.rb:98:in `run_examples'
    from /Library/Ruby/Gems/1.8/gems/rspec-1.1.9/lib/spec.rb:21:in `run'
    from /Library/Ruby/Gems/1.8/gems/rspec-1.1.9/lib/spec/runner.rb:191:in `register_at_exit_hook'
    from /usr/bin/rake:19
The ways to get your head around the bug is placing the rspec-rails before the rspc:
config.gem 'rspec-rails', :lib => "spec/rails", :version => '1.1.11'
config.gem 'rspec', :lib => "spec", :version => '1.1.11'
Alternatively, only include rspec-rails would install rspec by default.

RubyGem update on Leopard 0

Posted by jay

I have a RubyGem version 1.2.0 installed on Leopard. If you would like to update RubyGems to a newer version, the RubyGem user guide suggests for modern versions( >0.8.5 ) can use the following command:
gem update --system
But, console told me the 1.2.0 is the latest version – Nothing to update! The work around is to use install rubygem-update:
gem install rubygems-update
update_rubygems
Check installed version:
MBP:~ Jay$ gem --version
1.3.1
So now, I’m able to pull the latest rSpec plugin into my Rails project.

Frustrating User Experiences: Live Mail 0

Posted by jay

I used to be a Hotmail user for many years. Since gmail support SMTP, IMAP and more fancy features, I made the switch over. Last week, I had chance to send an email for a friend using Windows Live Mail, I wasn’t suppised that the general spead was faster while the auto spam filtering isn’t improved much.

Anyway, I created a new mail, typed in title and text. It’s natural that all the tool links should located on top of the mail body area. Send and Save button are the end of writing process, they should be logically located at bottom of the text area. So I spend a few seconds to find the Send button, finally found it on top of the menu. I know this is similar to other email client (e.g. Outlook) on windows. This is acceptable because they provide shortcut for executing the send action, while on Live mail, there is no such indication of sending shortcut.

a few alternative improvements can be made:
  • make the Send button standout (use bigger text or darker colour)
  • adding shortcut to the send action
  • move Send button to the end of the mailing body area.

Gmail Video Chat 0

Posted by jay

Google最近总是别出新意,前一阵子出了自家的浏览器Chrome,现在又在Gmail中增加语音和视频聊天。首先需要安装一个外制的挂件,安装文件支持多个平台包括Windows,Mac,浏览器支持FF 2.0+, IE 6.0+, Safari 3.0+, 当然也包括自家的Google Chrome,Opera却没有在支持咧表中出现。理论上可以支持双向的Broswer和Gtalk或者Browser和Browser之间的视频连接。

开发语音视频聊天功能的原因之一是由于文字像笑脸只类的表情无法真正表达用户的心情。新功能必定对其他的social network产生影响,比如Facebook和MySpace,他们是否也要考虑开发一个在浏览器中运行的语音和视频聊天平台?Google的优势在于可以将功能利用的其他的服务中,比较期待以下一些应用:

  • 比如在iGoogle中显示视频聊天
  • 提供聊天功能的API
  • Analystics中产生联系人的列表
  • Offline video message,对方离线的时候留视频的消息。

如果有人尝试过Gmail视频最多能达到多少人同时聊天的,麻烦你留个消息告诉我结果。

WordPress the_excerpt Plugin 0

Posted by jay

Recently, I was looking for a solution for extracting post text by defining the length of the string. WordPress offers two useful functions:
  • the_content(): returns the full content of a post
  • the_excerpt(): returns a fixed extracted text from a post, but no parameter option is provided.
The idea is to write a better function that has a few optional parameters to extract text from an entry. I found an “old” plugin has done all the nice jobs for the developes. It’s old because it’s not updated since March 2005. However, the plugin still works with the latest WordPress release. If you ever need such function, take a look “the excerpt reloaded”. Below is quoted documentation from author’s website.

Parameters:

excerpt_length
(integer) Number of words to display before ending the excerpt. Default is 120.
allowedtags
(string) Defines which HTML tags to retain in excerpt. Use the format '<img>'. For multiple tags, enter as single string: '<a><img>'. Default is '<a>'.
filter_type
(string) Defines how WordPress should filter/format an excerpt’s content. Options are based on content/excerpt tags: 'content', 'content_rss', 'excerpt', 'excerpt_rss'. Set to 'none' to display raw content. Default is 'excerpt'.
use_more_link
(boolean) Should the “more” link be displayed (TRUE) or not (FALSE). If set to false, function displays ellipsis (…) if content more than that displayed; neither link nor ellipsis displays if output is less than excerpt_length; Defaults to TRUE.
more_link_text
(string) If use_more_link is set to TRUE, set this to define what text to use for the link. Default is '(more...)‘.
force_more_link
(boolean) Display more link (TRUE) or not (FALSE), even when excerpt is less then excerpt_length. Defaults to FALSE.
fakeit
(integer) Use content as excerpt (1) or not (0) if excerpt is empty. Set to 2 to force content as excerpt under all conditions. Defaults to 1.
fix_tags
(boolean) “Repair” HTML tag elements (TRUE) or don’t (FALSE). This is implemented to deal with improperly closed tags which may be caused by excerpt_length. If fix_tags is set to FALSE, the plugin will not attempt XHTML validation and repair on improperly closed tags (due to excerpt_length breaking them in mid-element). Defaults to TRUE.

mySQL: Error 1045 0

Posted by jay

If you get this error (in phpMyAdmin or other operation) after setting up a MySQL password:
ERROR 1045: Access denied for user: 'root@localhost' (Using password: NO)
This might caused by phpMyAdmin’s configuration doesn’t have the new password. If using XAMPP, you need to update the /Applications/xampp/xamppfiles/phpmyadmin/config.inc.php for the phpMyAdmin:
$cfg['Servers'][$i]['password'] = 'YOURPASSWORD';

Change the YOURPASSWORD to the password you set before.

Also the /Applications/xampp/etc/my.cnf should be updated accordingly. The configration file specifies mysql’s setting. So dig in the file and update the settings:
# The following options will be passed to all MySQL clients
[client]
password    = YOURPASSWORD
port        = 3306
socket    = /Applications/xampp/xamppfiles/var/mysql/mysql.sock

Same here update the password.

Although setting up securities for local development is a little hassle as you need to type in password etc etc, I still recommend to set it properly.

VirtualHost browser cache 0

Posted by jay

Setting up a virtual host on PC, Mac or Linux isn’t difficult, but the browser cache problem drives me crazy. Apart from editing the /etc/hosts mappings and httpd.conf, you need to restart both Apache and browser. Refreshing the browser(Firefox) doesn’t clean the cache, so the result will be always add /xampp/index.php at the end of the virtual host name.