0

I'm using ruby 2.6.5 on my local machine. I also use the same ruby version on heroku machine.

However i got weird error on using heroku.

if i defined a method like:

def current_admin
  @current_admin ||= 'yana'
end

It works perfectly on my machine, on heroku it will raise a NameError:

NameError (`@` is not allowed as an instance variable name)

however when i do:

def current_admin
  return @current_admin if defined?(@current_admin)
  @current_admin = 'yana'
end

It works on both machine.

What exactly is the difference that cause first syntax fails on heroku?

* Update *

The diff i made to make it work on heroku.

   def current_account
-    @current_account ||= AccountSession.find
+    return @current_account if defined? @current_account
+
+    @current_account = AccountSession.find
   end
Yana Agun Siswanto
  • 1,932
  • 18
  • 30
  • 8
    This doesn't seem possible. Exactly which line of code was the `NameError` on? – Casper Nov 17 '19 at 14:35
  • 1
    Once I had messed up with Zero-width space(https://en.wikipedia.org/wiki/Zero-width_space) Try to clear @current_admin ||= 'yana' row completely and retype it again. – Serhii Nadolynskyi Nov 17 '19 at 20:08
  • @Casper I probably messed up. The error was on `@current_admin ||= 'yana'`. I have edited the code to remove unnecessary context. However, I might be doing it wrong. I updated the question with the diff from the source code. – Yana Agun Siswanto Nov 18 '19 at 02:27
  • @SerhiiNadolynskyi thank you. That probably the problem. I have fixed it. I followed the coding style used in authlogic instead. However, how did you debug it so that you get into the conclusion that Zero-width space is the problem? – Yana Agun Siswanto Nov 18 '19 at 02:31
  • @YanaAgunSiswanto I do not remember how exactly I figured that out. Probably I saw some difference in `git diff` or something like that. – Serhii Nadolynskyi Nov 26 '19 at 10:20

1 Answers1

3

I have no idea about Heroku glitches, but here is the answer on what exactly is the difference.

@current_admin ||= 42

The line above is the exact equivalent of @current_admin = @current_admin || 42. That said, the value will be reset to 42 when @current_admin is falsey, aka _either false or nil.

@defined would reset the value if and only this instance variable was not previously declared within current scope. Even nil would stay as is if it was explicitly set before.

defined? @current_admin
#⇒ nil
@current_admin = nil
defined? @current_admin
#⇒ "instance-variable"
Aleksei Matiushkin
  • 119,336
  • 10
  • 100
  • 160