Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

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

ruby on rails - Why isn't method defined in application_helper available to use in the view?

When I put this in the application_helper.rb, it is available to use in the view

def foo
  "bar"
end

But when I put this in application_helper.rb it is not available to use in the view (instead: NoMethodError undefined method)

def nice_datetime 
  self.strftime('%d %b %-I:%M%p %Z')
end

Why is the first method available in the view and the second method not available in the view?


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

1 Answer

0 votes
by (71.8m points)

The self part is the problem, it is referencing the view itself* and that doesn't have a method called strftime. You can fix it somewhat by doing

def nice_datetime(date)
  date.strftime('...')
end

I would however urge you to look into localization. Which would work something like this, just a very basic setup.

# config/locales/en.yml
en:
  time:
    formats:
      short: "%H:%M"
<p><%= l Time.now, format: :short %></p>

* That might not be strictly true, I can't remember exactly how helpers are included in the view files, but for sake of this argument is close enough.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...