Is it possible to handle 'magic' property assignments a'la PHP?

Jacob Carlborg doob at me.com
Mon Jan 6 01:49:51 PST 2014


On 2014-01-05 22:44, Philippe Sigaud wrote:

> I didn't know that, thanks. I read it during the holidays in Martin
> Fowler's book on DSL, but indeed that book is from 2005, IIRC.

That's a bit old :). According to this site[1] Rails 1.0 was released in 
December 2005. Rails 4.0 was released in June 2013.

I think there are two reasons why they deprecated that syntax:

* They want to avoid method_missing (same as opDispatch in D)

* They want to have the name of a column close to the value of that 
column. Example:

Table.find_first_by_fist_name_and_last_name("foo", "bar")

In the above example the values and the columns they belongs to are 
quite disconnected. The column names are far to the right and the values 
are far to the left. With the AA syntax you get the column name and its 
value closely connected. It's clear to see which value belongs to which 
column.

> Yes, using AA is a nice idea, which avoids introducing first_name in
> the current scope.

I have to admit that it looks a lot better in Ruby than in D.

> Some other possibilities could be:
>
> Table.where!(e => e.first_name == "foo").first; // Similar to std.range.filter

This is the one I like best and it's possible to have the same syntax in 
Ruby as well with a plugin, Squeel[2]. This allows to have more advanced 
quires containing "or" and negation.

The problem is it's basically only equality that works with this syntax. 
You cannot overload !=, && or || in D. You could of course use method 
names like "equals", "and" and "or".

In Squeel they "solved" it by overloading | and & to mean "or" and 
"and". That causes other problems with operator precedence, one needs to 
wrap everything in parentheses.

In D we would need more finer grained control of operator overloading, 
like overload == separately from !=. Or, I come back to this all the 
time, AST macros.

> Table.where.first_name!(e => e == "foo").first;

If I look at the API in Rails I think this could cause some conflicts 
with all the methods that are available on the object returned by 
Table.where.

> Table.where((string first_name) => first_name == "foo").first; // By
> extracting the parameter name
>
> The syntax is heavier than your example, but some nice logic can put
> into a closure.

Same problem as above.

> Some also advocate:
>
> Table.where.first_name.equals("foo").first;
>
> But I find it a bit too clunky.

Same problem as above.

[1] http://railsapps.github.io/rails-release-history.html
[2] https://github.com/activerecord-hackery/squeel

-- 
/Jacob Carlborg


More information about the Digitalmars-d-learn mailing list