ryah ([info]four) wrote,
@ 2007-11-07 01:49:00
Previous Entry  Add to memories!  Tell a Friend!  Next Entry
Current mood::(
Entry tags:method_args, projects, ruby

method args
Awhile ago I wrote a hack which dived deep into Ruby's parse tree to extract the names of a method's arguments. So you could do things like this

  require 'method_args'
  class X
    def hello(foo, bar)
      nil
    end
  end
  x = X.new
  m = x.method(:hello)
  m.args  # => [:foo, :bar]
I can't tell you how amazingly hackish my hack to make this work is. Exposing private data structures, blindly iterating through mysterious linked lists, etc. (Check out the code.) But it worked and I felt great having finished it.

This was all in the hope that in Merb, incoming HTTP parameters like http://a.com/blah?foo=bar&hello=world would not need to be stuffed blindly into a hash (params = {'foo' => 'bar', 'hello' => 'world' }) and then passed to the action for http://a.com/blah
  def blah_action
    @useful = lookup_in_database(params['foo'])
    # note that params['hello'] is ignored
    render 'blah.erb'
  end
Rather one could use the syntax of Ruby to say which URL parameters it needed with method parameters! That is the action could be written this way
  def blah_action(foo)
    @useful = lookup_in_database(foo)
    # note that 'hello' isn't used and thus doesn't exist
    render 'blah.erb'
  end
The problem is that now the Merb team has actually decided to have this feature, but has run into a snag. What happens when a function looks like
  def foo(bar, baz = 1, bat = 2)
    ...
  end
and your URL looks like http://a.com/foo?bar=5&bat=6. Without knowing the default value of the middle argument baz, we cannot call the function.

After all that hacking it appears my module is still useless. Furthermore I don't have the inclination or stamina to jump into that mess again and add the feature. :(



(Post a new comment)


(Anonymous)
2007-11-07 02:26 am UTC (link)
What if you require all defaults to be nil and set them via ||= in the function body instead?

(Reply to this) (Thread)


(Anonymous)
2007-11-07 02:27 am UTC (link)
Also this is no different than regular Ruby which prevents you from using a later parameter without fully specifying all the preceding ones.

(Reply to this) (Parent)


[info]four
2007-11-07 07:24 am UTC (link)
we could do that but the Merb people want this "full" interface, the possibility to have default values

(Reply to this) (Parent)


Create an Account
Forgot your login?
Login w/ OpenID
English • Español • Deutsch • Русский…