Pass JavaScript variables to Rails controller

Posted by jay on April 13, 2009

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

Posted by jay on February 16, 2009

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

Posted by jay on February 01, 2009

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.
  • 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. (Added on March 24 2009)
  • rails.raaum.org Taylor suggested a very compact Rails documentation site. It’s actually a site that lists some useful information for developers including good podcasts, links and posts. So check this out see if you can find any good topics.(Added on July 21 2010)

“Fork Ruby” Summary (RubyConf 2008)

Posted by jay on December 30, 2008

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.

Configure Rails migration version type

Posted by jay on December 02, 2008

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

Posted by jay on November 29, 2008

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 => "spec", :version => '1.1.11'
config.gem 'rspec-rails', :lib => "spec/rails", :version => '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

Posted by jay on November 27, 2008

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.

Symfony and Ruby on Rail

Posted by jay on April 15, 2008

研究过PHP下的Symfony, 再看Ruby on Rail的时候, 发现两者都有不少的相似性.

首先他们都用到MVC的架构设计整个项目, 作为Web Application来说, 这样可以将class library, layout view, handler清清楚楚的分开,有助于多人开发,和日常维护。 如果比较过两者library的结构,他们也有相近之处。 从创建项目到编辑项目设置等等。 比如, 创建项目时, 他们都会创建一系列的文件夹和默认文件, 然后可以自己创建module, 都有位置防止plugins。做数据库的时候,也可以用.xml 或者.yml导出 Sql store procedures.

那到底哪个比较好一些。 这里有一边文章对比一些MVC frameworks的性能, 不足的是, Bench mark只不过是一个参照, 完全不能说明其他的情况, 比如error handling的性能, 每个framework都有各自的优化设置, symfony deployment的时候就有优化的设置. 在Google doc上到有一片比较全面的文章比较Rail和Django, 对与一个新的项目选择framework有一定的帮助.