matthewrudy / memoist

ActiveSupport::Memoizable with a few enhancements
MIT License
920 stars 99 forks source link

Hash parameters not supported #28

Closed JacobEvelyn closed 9 years ago

JacobEvelyn commented 9 years ago

I just tried this:

def foo(bar: bar)
  ...
end
memoize :foo

and received errors. I haven't gotten a chance to look into it much yet and I'd be happy to write a fix; just wanted to make sure this was recorded somewhere so I didn't forget about it :)

matthewrudy commented 9 years ago

Hi @JacobEvelyn, I just pushed 0.11.0 which has a fix like this. Can you see if it fixes your problem?

JacobEvelyn commented 9 years ago

Unfortunately, it doesn't seem to. The error I get is: NameError: undefined local variable or method 'bar'

al2o3cr commented 9 years ago

@JacobEvelyn - FWIW, the NameError is because there's no method bar in scope. Ruby's keyword args work a little differently than similar implementations (selectors in Objective C, for instance). The value on the right-hand side of the colon is the default, not the local name.

This is legal:

def foo(bar:)
   # bar is a required keyword argument
end

as is this:

def foo(bar: 0)
  # bar is an optional keyword argument, defaults to 0
end

or even

def wat(x, bar: x*2)
  puts bar
end
# you can call this function as
#   wat(5)
# in which case it prints "10"
# or like
#  wat(5, bar: "nope")
# in which case it prints "nope"

In every case, the keyword arg appears inside the function's scope as a local variable with the same name. (bar in all the above)

JacobEvelyn commented 9 years ago

Ah, right. Silly me. Good explanation, thanks!