HTML_QuickForm in .... Rails ?

Posted almost 7 years back at work.rowanhick.com

Caution Thinking Out Aloud: Okay the purists have just decided to kill me. Let the religious wars begin ! No seriously, everytime I do some coding in an old PHP app which is heavily dependent on HTML_QuickForm, I keep questioning how possible would it be to convert it across to Rails, and whether any other persons like myself would think all of their Christmases have come at once. Here's my hopefully rational thought processes behind this. Rails is a fantastic CRUD machine. If you want to build single model forms with validations in them, absolutely beautiful. Nothing could feel more clean and make you as a developer go 'thats sweet'. Fantastic. Now try and do a model-less form, with validations, or combine multiple models within one form. Things like the presenter pattern get bandied about. Real world case example - a form to choose options for defining a report. Nothing that you want to put in a model as it's not a represenation of a 'thing' (although some may argue it is). I wonder and am sitting on the fence of, whether to try implementing quickform for rails. For those that haven't been exposed to it, in a nutshell it's a brilliant little php library that lets you create a representation of a form, with rules, pass the form into a renderer which dumps out the html on a page, but that's not all, it assists you in processing the form on submission. So some code can look like this (not syntactically correct, but close enough), which does all of the hard work of writing out html, setting up client side js, and server side processing. //page myform.php $myform = new HtmlQuickForm('form_name', 'myform.php'); $abc = $myform->addElement('text', 'product_name', 'Product Name:'); $myform->addRule('product_name', 'required', 'You must enter a product name'); if ($myform->validate()) { //process form var_dump( $abc->getValue() ); } else { //setup form $abc->setValue('123') } // then in any template which dumps out the rails code $myForm->display(); It doesn't seem like much, but put half a dozen or more options on the form, different processing rules, and suddenly it's done a lot of the heavy lifting for you. What would it take to add this to Rails ? How would (I personally) fit it in. It doesn't really sit within either the model, view, or controller. The view should render the output, it doesn't really fit within a model as it's not a representation of a thing. It most closely sits in the controller, but you don't really want to clutter the controller with your form models. Here's some thoughts An initial idea, with everything defined in the controller, then dumped into the view by a @my_form.output class FormController < Application def do_form get_form if @myForm.posted #do stuff else #populate stuff end end protected def create_report @myform = RFormBuilder.new do |f| f.call_back_url = { :controller => 'form', :action => 'do_form' } f.name = 'myform' end @myform.add_text( :name => 'product_name', :label => 'Product Name', :rule => { :required => :true, :msg => 'You must add this' } ) end end OR Maybe we add in a new folder in the main app /app/ /controllers /models /views /forms myform.rb And the treat myform.rb kinda like a model, but kinda not. class MyForm < RFormBuilder defaults :name => 'my_form', :call_back_url => '/myform' text_field :name => 'product_name', :label => 'Product Name', :required => :true #gets called when form is posted def validate return true if field_product_type == 'abc' end end # now in FormController def do_form get_form @my_form = MyForm.new if @myForm.valid #do stuff render :text => @my_form.field_product_name else #populate stuff end end What do you think ? Am I stark raving mad. Could this just work ? I think so and am willing to take up the challenge... Rowan

Optimising Symbol#to_proc

Posted almost 7 years back at Luke Redpath - Home

Whilst pairing with Paul the other day I noticed that he preferred not to use Symbol#to_proc; on asking why, he told me it was because of the unnecessary performance hit that Symbol#to_proc imposed.

Now I’m not one for premature optimisation, but with an idiom like Symbol#to_proc likely to be used throughout a codebase, performance hits like this add up and as things stand, the Rails implementation of Symbol#to_proc is pretty expensive:

require 'benchmark'
require 'rubygems'
require 'active_support'

BIG_ARRAY = ['x'] * 1000000

Benchmark.bm do |bm|
  bm.report("Standard block") do
    BIG_ARRAY.map { |c| c.upcase }
  end
  
  bm.report("Symbol#to_proc") do
    BIG_ARRAY.map(&:upcase)
  end
end

Output on my 2Ghz quad-core Mac Pro:

              user     system      total        real
Standard block  0.720000   0.060000   0.780000 (  0.772927)
Symbol#to_proc  3.030000   0.010000   3.040000 (  3.040889)

Ouch. That’s roughly four times slower. -Based on my naive understanding of how Symbol#to_proc was implemented, it figured that the bottleneck was the creation of a new Proc object for every iteration; the proc doesn’t need to change for each iteration so surely we could just memoize it-?

Update: It seems that my initial assumption was incorrect; to_proc is in fact only called once. The real issue here is not the instantiation of a new proc, but the Rails implementation. Rails uses this slightly more complicated implementation in order to support passing of multiple arguments with the method call:

Proc.new { |*args| args.shift.__send__(self, *args) }

This allows you to do a few neat things with multiple elements of a collection like [1, 2, 3].inject(&:+) but I consider this supporting an edge case at the expense of performance.

I’ve never found myself in need of the functionality provided by Rails’ implementation (I didn’t even know it was supported) but I do find myself using the obj.map(&:method) idiom a lot so the following simplified implementation suits me just fine:

class Symbol
  def to_proc
    proc { |obj| obj.__send__(self) }
  end
end

The performance gain is significant:

user     system      total        real
Symbol#to_proc  0.910000   0.010000   0.920000 (  0.916718)

The implementation itself is trivial but I’ve made it available on pastie – just drop it into a file somewhere in your Rails lib folder. If I find the time, I will try and package it up as a basic Rails plugin too. It’s worth bearing in mind that Ruby 1.9’s implementation will probably support the passing of arguments like the Rails implementation but hopefully it should be much faster.

The performance of Symbol#to_proc has also been brought up on Pratik Naik’s blog and this Rails ticket.

Update: Some of my original assumptions about the way Ruby invokes to_proc were incorrect and I have updated my article accordingly.

Episode 81: Fixtures in Rails 2.0

Posted almost 7 years back at Railscasts

In Rails 2.0, fixtures see many improvements which makes them much easier to manage. Watch this episode for details.

What makes code beautiful?

Posted almost 7 years back at Saaien Tist

Saw this webcast a couple of weeks ago where Marcel Molina explains the notion of beautiful code. And I really recommend anyone writing code to have a look at it (totally irrespective of the fact he uses a ruby example...). If you look at the progress bar of the presentation, it looks like it's really long, but only the first half is the actual presentation, followed by a lengthy discussion. (The last few minutes have a nice wrap-up by Chad Fowler.)

The talk is basically split into two parts: (a) what is beauty, and (b) how does that apply to coding?

What is beauty?

After going into the history of what philosophers like Plate, Rousseau and others found beautiful, Molina focusses on the three rules set out by Thomas Aquinas: proportion, integrity and clarity. Things that are beautiful comply to these rules. The examples that Molina uses:

  • proportion: suppose the fingers on your hand would be twice or half as long. Wouldn't really be beautiful, would it? Think 'golden ratio' here.
  • integrity: a thing has to be fit for its purpose. Take for example a hammer made of crystal. It might look beautiful, but can't do what it's supposed to. The appearance of beauty is not necessarily the same as real beauty.
  • clarity: it should be clear what something is/does.

How does it apply to coding?

It's straightforward to apply these principles to programming code. First, let's take a look at proportion. The code for simple functionality should be short. Not long. To add two numbers should be a single call. Molina gives an example here of how that had to be done in assembly. Really way too much coding going on to just do that. Here at work, the phrase "Jan can do that in 2 lines of ruby" are often heard (fortunately a little bit less, lately (pfew)). I feel that's not because I'm a code hacker, but because Ruby makes it simple to do simple things. Perl has the same characteristic, but at a price (I'll come back to that later).
Secondly, there's integrity. Does your code do what it's supposed to do? That's the most widely-used notion of good code: do the tests run? But code that does what it has to do can be still be ugly if it doesn't comply to the other principles. Spaghetti, anyone?
Thirdly, there's clarity. How much of your code can your fellow programmers understand by looking at it for less than a day? The fact itself that you have to explain your code might sometimes indicate that you're violating this rule.

One quirk of applying these principles to programming code, is that there's a clear trade-off between them. Some hacked together code might be very proportionate to what it's supposed to be, but in doing so it might become obfuscated and therefore violate the clarity principle. I must say that I've often found it difficult to understand my own perl code after a couple of weeks of not looking at it. Most of this can be attributed to the fact that the language itself needs you to write less clear code ($_, the way objects are implemented, ...).

When you see smelly code, chances are it's one of these three that are the problem.

Why does this matter?

To paraphrase Rousseau: Good code is beautiful code in action. Creating beautiful code (by the above principles) is no guarantee for good code, but it's a pretty good start...

Note: There's a book on Beautiful Code as well, and apparently there's a chapter by Lincoln Stein on his Bio::Graphics library. Better get my hands on that book for ideas for the ruby version.

Book Review: Google Maps Applications

Posted almost 7 years back at Beyond The Type - Home

Reviewing: http://www.apress.com/book/view/1590597079

Google Maps book This is a pretty good all round book with plenty of examples and some hardcore(ish) trig at the back if you want to get down and dirty and do more complex mapping.

As the title suggests you are taken on a journey from simple map based applications to more advanced concepts. It’s not really a book that you can dip in and out of, however, if you are willing to spend some time with it then there is a wealth of information to explore.

In particular Chapter 7 “Optimizing and scaling for larger data sets” offers great tips on how to handle different data set sizes and tackles subjects such as bounding, clustering, and proximity based techniques. Chapter 9 “Advanced tips and tricks” is also a really great read with lots useful practical nuggets of information for new ideas on where to take your application next.

Sadly the book lacks an introduction chapter giving a summary of all the cool things that are covered within it. In many cases diagrams would be better placed to summarise long sections of text. Source code examples listed are presented without line numbers and often without a direct reference to the sample files. Doing so would have helped to split the main text up from the source and made the book an easier read.

Criticisms aside it’s a good first step into world of Google Maps Applications with Rails and AJAX. There is a lot of interesting material with pretty much something for developers of all levels to benefit from.

Further Information

Publishers site:

Book Review: Google Maps Applications

Posted almost 7 years back at Beyond The Type - Home

Reviewing: http://www.apress.com/book/view/1590597079

Google Maps book This is a pretty good all round book with plenty of examples and some hardcore(ish) trig at the back if you want to get down and dirty and do more complex mapping.

As the title suggests you are taken on a journey from simple map based applications to more advanced concepts. It’s not really a book that you can dip in and out of, however, if you are willing to spend some time with it then there is a wealth of information to explore.

In particular Chapter 7 “Optimizing and scaling for larger data sets” offers great tips on how to handle different data set sizes and tackles subjects such as bounding, clustering, and proximity based techniques. Chapter 9 “Advanced tips and tricks” is also a really great read with lots useful practical nuggets of information for new ideas on where to take your application next.

Sadly the book lacks an introduction chapter giving a summary of all the cool things that are covered within it. In many cases diagrams would be better placed to summarise long sections of text. Source code examples listed are presented without line numbers and often without a direct reference to the sample files. Doing so would have helped to split the main text up from the source and made the book an easier read.

Criticisms aside it’s a good first step into world of Google Maps Applications with Rails and AJAX. There is a lot of interesting material with pretty much something for developers of all levels to benefit from.

Further Information

Publishers site:

RSpec and Inline RJS

Posted almost 7 years back at Jonathan.inspect

Rails give us the ability to write inline RJS via render :update syntax, as in :

1
2
3
render :update do |page|
  page['addressPreviewStatus'].update 'Address Not Found'
end

Previous code will update the content of tag with “addressPreviewStatus” id with ‘Address Not Found’.

But how can we spec that out ? I needed to search a little as there seems to be very little examples.

First in rails there is a special assertion assert_select_rjs, merged from the assert_select plugin, it let you test your RJS with a syntax similar to RJS itself. RSpecOnRails has a special matcher wrapping assert_select_rjs : has_rjs.

You can use it on response to specify what should be generated, for exemple you can :

1
2
3
4
5
6
7
8
# Specify response should contains an update or insert of some kind
response.should have_rjs

# Specify response should contains an update or insert for the tag with given id
response.should have_rjs('id')

# Specify response should contains a specific update, insert, etc. for the given tag
response.should have_rjs(:replace, 'id')

You get the point. Now, a nice syntax allows you to write RJS this way :

1
2
3
render :update do |page|
  page['id'].update('replacement text')
end

So my first try was to use :


response.should have_rjs(:update, 'id', 'replacement text')

but this fail miserably with an error Unknown RJS statement type update. I tried different syntax but none worked.

Finally browsing through source of assert_select_rjs I found what I was looking for. When using this syntax you should use one of :chained_replace or :chained_replace_html depending what you want to test :replace or :update.

Now here is the solution :


response.should have_rjs(:chained_replace_html, 'id', 'replacement text')

Links For 11.24.07

Posted almost 7 years back at zerosum dirt(nap) - Home

Next directions - update

Posted almost 7 years back at The Hobo Blog

A few days ago we announced our intention to break Hobo up into various self-contained sub-projects. I just though I’d give you an update on our plans.

The first plan was to get started with the big break-up ASAP. That would obviously push back the documentation I’ve been promising to do. The idea was to provide a reasonable level of documentation for each sub-project as it was released.

Slight change of plan :-)

I’m not in the #hobo channel all that often, but James is, just 2 meters to my left. So I’m well aware that there are a bunch of you that are determined to keep making progress with Hobo with docs or without.

With that in mind, I’ve come around to the idea that getting at least some docs out there for you folk is really the top priority. I think the best way to address this issue quickly is with some example code.

With that goal in mind, we’re announcing a new project today – beta.hobocentral.net (don’t go there now, there’s nothing there yet!).

We’re going to build a new version of hobocentral.net in Rails + Hobo. It will have the current features: blog, forums, documentation (cough) etc. In time we’ll add a whole host of new features like the long-promised tag library, user-extensible documentation and more. This is going to be an open-source project, and it’s going to serve a dual purpose. As well as getting us a better hobocentral.net, the code will be extensively commented and the whole thing will server as a decent real-world example of how to build a Hobo app. The documentation will be implemented by the documentation. It’s all a bit meta-circular, which you gotta love :-)

The point of the beta.hobocentral.net domain is that we can whack this app up really soon, and continue using the existing Wordpress based site until the new one cuts the mustard.

There is one small hold-up I’m afraid (groan). We’ve got this little outstanding DRYML issue with CamelCaseTags. From James’ experience trying to explain template tags on #hobo, it’s clear that this needs to be cleaned up right now. So I’m going to work on that first (right now in fact), and then start on beta.hobocentral.net

You should see the first cut of beta.hobocentral.net go up next week, delivering on my promise to provide some documentation in November!

Next directions - update

Posted almost 7 years back at The Hobo Blog

A few days ago we announced our intention to break Hobo up into various self-contained sub-projects. I just though I’d give you an update on our plans.

The first plan was to get started with the big break-up ASAP. That would obviously push back the documentation I’ve been promising to do. The idea was to provide a reasonable level of documentation for each sub-project as it was released.

Slight change of plan :-)

I’m not in the #hobo channel all that often, but James is, just 2 meters to my left. So I’m well aware that there are a bunch of you that are determined to keep making progress with Hobo with docs or without.

With that in mind, I’ve come around to the idea that getting at least some docs out there for you folk is really the top priority. I think the best way to address this issue quickly is with some example code.

With that goal in mind, we’re announcing a new project today – beta.hobocentral.net (don’t go there now, there’s nothing there yet!).

We’re going to build a new version of hobocentral.net in Rails + Hobo. It will have the current features: blog, forums, documentation (cough) etc. In time we’ll add a whole host of new features like the long-promised tag library, user-extensible documentation and more. This is going to be an open-source project, and it’s going to serve a dual purpose. As well as getting us a better hobocentral.net, the code will be extensively commented and the whole thing will server as a decent real-world example of how to build a Hobo app. The documentation will be implemented by the documentation. It’s all a bit meta-circular, which you gotta love :-)

The point of the beta.hobocentral.net domain is that we can whack this app up really soon, and continue using the existing Wordpress based site until the new one cuts the mustard.

There is one small hold-up I’m afraid (groan). We’ve got this little outstanding DRYML issue with CamelCaseTags. From James’ experience trying to explain template tags on #hobo, it’s clear that this needs to be cleaned up right now. So I’m going to work on that first (right now in fact), and then start on beta.hobocentral.net

You should see the first cut of beta.hobocentral.net go up next week, delivering on my promise to provide some documentation in November!

@media Ajax

Posted almost 7 years back at danwebb.net - Home

Well, that turned out rather nicely I must say. Really high quality presentations and great attendees – I really hope that Patrick makes it happen again. Here are the slides from my presentation: Metaprogramming JavaScript.

<object height="355" width="425"><param /><param /><param /><embed src="http://static.slideshare.net/swf/ssplayer2.swf?doc=metaprogramming-javascript-1195638729182448-3" height="355" width="425"></embed></object>

In other news, Low Pro 0.5 is nearly ready to rock. The new version is quite a lot smaller as Prototype 1.6 has solved so many of the things I used to fix with Low Pro. It does however have a few nice new features. Watch this space.

@media Ajax

Posted almost 7 years back at danwebb.net - Home

Well, that turned out rather nicely I must say. Really high quality presentations and great attendees – I really hope that Patrick makes it happen again. Here are the slides from my presentation: Metaprogramming JavaScript.

<object height="355" width="425"><param /><param /><param /><embed src="http://static.slideshare.net/swf/ssplayer2.swf?doc=metaprogramming-javascript-1195638729182448-3" height="355" width="425"></embed></object>

In other news, Low Pro 0.5 is nearly ready to rock. The new version is quite a lot smaller as Prototype 1.6 has solved so many of the things I used to fix with Low Pro. It does however have a few nice new features. Watch this space.

Ruby Method Visibility

Posted almost 7 years back at zerosum dirt(nap) - Home

In Java (and most OO languages), declaring a method as private means that the method can only be accessed within the context of the defining class. Similarly, protected means that the method can only be accessed from that class or any of its subclasses.

In Ruby, things are a bit different. Both private and protected methods can be called by any instance of the defining class and its subclasses. Inheritance plays absolutely no role in determining the visibility of a method. The difference instead is that private methods can never be called with an explicit receiver, even if the receiver is self. This means that it’s not possible to access another object’s private methods, even if the object is of the same type as the caller. A private method must be called from within the calling object.

Consider the following example:

class Person
  def public_method
    "public"
  end

  protected
  def protected_method
    "protected"
  end

  private
  def private_method
    "private"
  end
end

class SalesPerson < Person
  def check_protected_method_explicit_receiver
    "#{self.protected_method} method OK with explicit receiver"
  rescue
    "failure accessing protected method with explicit receiver"
  end

  def check_protected_method_implicit_receiver
    "#{protected_method} method OK with implicit receiver"
  rescue
    "failure accessing protected method with implicit receiver"
  end

  def check_private_method_explicit_receiver
    "#{self.private_method} method OK with explicit receiver"
  rescue
    "failure accessing private method with explicit receiver"
  end

  def check_private_method_implicit_receiver
    "#{private_method} method OK with implicit receiver"
  rescue
    "failure accessing private method with implicit receiver"
  end
end

The public method can of course be accessed from anywhere (in this case, outside the class with an explicit receiver) and both private and protected methods of Person will obviously raise a NoMethodError.

Person.new.public_method
=> "public"
Person.new.private_method
=> NoMethodError: private method `private_method' called for #<Person:0x6ec698>
Person.new.protected_method
=> NoMethodError: protected method `protected_method' called for #<Person:0x6ea5c8>

So the protected method cannot be accessed outside of the class or it’s subclass, but from within the subclass, using it with either an implicit or explicit receiver works fine:

SalesPerson.new.check_protected_method_explicit_receiver
=> "protected method OK with explicit receiver"
SalesPerson.new.check_protected_method_implicit_receiver
=> "protected method OK with implicit receiver"

The private method can also be called from the subclass, but note how it only works with an implicit receiver:

SalesPerson.new.check_private_method_explicit_receiver
=> "failure accessing private method with explicit receiver"
SalesPerson.new.check_private_method_implicit_receiver
=> "private method OK with implicit receiver"

This also means you can do stuff like:

class Person
  def ==(other)
    protected_method == other.protected_method
  end
end

x = SalesPerson.new
y = Person.new
x == y
=> true

We’re accessing the protected_method of another class instance that shares our type here, specifying an explicit receiver. If you were to try to use private_method instead, a NoMethodError would be raised. You could also just call other.send("private_method") if you really wanted to, violating our encapsulation and angering the gods of object orientation. This is only a “little sin” though, and can be permissible if the situation calls for it (like, cough cough, my latest commit to DataMapper).

In summary, method visibility and access control can be a bit confusing at first, especially if you’re coming over to Ruby from some other OO language. If you’re still confused, there’s more information available here and here. Do yourself a favor and make sure you understand, cuz it’s important stuff!

Ryan Daigle - Ruby on Rails Podcast

Posted almost 7 years back at Ruby on Rails Podcast

Ryan Daigle talks about his blog, the upcoming Rails 2.0, and freelancing with style.

VirtueDesktops alternative for OS X 10.5 (Leopard)

Posted almost 7 years back at Beyond The Type - Home

Just upgraded to Leopard and sad at the loss of VirtueDestkops? Spaces not doing it for you? Read on…


Background

When Leopard was announced Spaces was touted as the replacement for VirtueDesktops. This lead to Tony Arnold the main developer of VirtueDesktops downing tools and declaring VirtueDesktops dead.

So everybody waited in anticipation for OS X 10.5… only to find Spaces not living up to their expectations.

So why the big fuss?

With the advent of 10.5 Apple has tightened up the code such that no other Desktop managers properly work on top of Leopard. This leaves many followers of VirtueDesktops little or no choice than maybe to change their working practices to Spaces or find alternatives….

1. HyperSpaces

From the creator of VirtueDesktops comes HyperSpaces. Unfortunately this isn’t set for launch until 2008 and it also isn’t clear if it will have the same rich feature set that VirtueDesktops has.

2. YouControlDesktops

YouControlDesktops has probably the closest functionality you are going to get to VirtueDesktops. The interface for configuring things isn’t as intuitive or slick as Virtue but it’s not such a big deal since you’ll not need to use it that often.

Currently there is a beta version for 10.5 that works pretty well but there is some kinks. Namely issues with the Dock not always getting context when it should.

So in summary the solution is not perfect but it’s the best I’ve found so far. Download the beta and provide the developers with feedback, hopefully we can help push this forward.