The Hpricot library allows the following syntax:
Hpricot(my_document)
This is not idiomatic Ruby, and a novice programmer might not know what it did, or how. UrbanHonking explains how, but James Robertson takes issue over why.
If you are going to bend a language's idiomatic usage, you should have a compelling reason, and I share James' view that this example is not compelling.
But other examples are compelling. In Ruby, I could say this:
class Person < ActiveRecord::Base
has_many = ["opinions"]
validates_presence_of("first_name")
end
Yuck. Better:
class Person < ActiveRecord::Base has_many :opinions validates_presence_of :first_name end
That's how it would look in Rails today. But I could do even more exotic things:
# no base-class, but has_many triggers mixin class Person has_many :opinions end
Or
Person = Model :has_many=>:opinions, :validates_presence_of=>:first_name
Or
# creates a Person class!!
person {has_many :opinions; validates_presence_of :first_name}
Or how about:
# creates MyDB::Person, MyDB::Opinion, & other classes automatically module MyDB tables :all naming_conventions :capitalized, :singular end
One of these choices is clearly better than all the others. (Which one?)
The unconventional wisdom here is that your syntax should be chosen for the domain, not by the language. In order for this to work, you must be able to think creatively about the domain you are working in.
The classic counter-argument is "our developers aren't smart/skilled/experienced enough to take advantage of this." Riiight. If your developers aren't skilled enough to think creatively about the domain you are working in, you have way bigger problems.
(Updated to fix typo in example five, thanks Scott!)
Comments
While teaching a workshop, someone pointed out that “belongs_to :article” should be more idiomatically written as “belongs_to Article”, in the manner of “relevance.is_a? Blog”.
I thought that was a valid observation, but it does break the reads-as-English nature of the plural form.
I disagree that Hpricot(document) is not idiomatic Ruby.
For example, Integer(‘1’) which creates an integer if the input is a valid representation of an integer.
By the same idiom, Hpricot takes a string representation of a structured document and converts it to an Hpricot.
This seems like a perfectly sensible use to me.
Your fifth Person example (# creates a Person class!!) is not valid Ruby syntax.
Scott: Thanks, I have fixed the typo.
topfunky – could you use constant_missing to handle the pluralized forms? Can’t decide if that would make things more or less confusing. :)