Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
498 views
in Technique[技术] by (71.8m points)

function - Should Rails helpers assume an instance variable exists or should they receive them as parameters?

I'm wondering if there's a specific programming principle (Demeter?) that supports the idea that Rails helpers should never use controller instance variables, rather, they should receive such variables as function parameters. For example, assume my ChickensController#squawk action creates an instance variable called @egg. Furthermore, assume the squawk view contains a call to a helper called cockadoodledoo, implemented like so:

def cockadoodledoo
  @egg.to_s
end

Would it be better or unnecessarily verbose to pass @egg as a parameter, such that the view calls cockadoodledoo(@egg) and for the helper to resemble:

def cockadoodledoo(egg)
  egg.to_s
end

I hope one of you happy hackers is bored enough on a Friday afternoon to assert an answer. Cockadoodledoo!

This question here is similar, but was never accurately answered.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Receive them as a param. Otherwise, as the app grows, it gets very difficult to trace where the instance vars are being set when refactoring, troubleshooting, etc.

Also, I believe there's a general best practice to only use instance vars in views within the initial template...and from there you should pass the var into helpers and other partials.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...