我在 ApplicationController 中有这个:
class ApplicationController < ActionController::Base
helper_method :nicename
def nicename(name)
# all entries in the DB are in lower case and need to be formated
# for dislay in views:
name.gsub(/[\s]/,'-').split("-").map {|m|m.capitalize}.join('-')
end
end
在我看来,我是这样调用 nicename 方法的:
<% l.authors.each do |m| %>
<%= nicename(m.firstname) %>
我应该如何编写方法才能在 View 中执行此操作:
<%= m.firstname.nicename %>
最佳答案
按照您的意愿执行此操作而不传递参数的唯一方法是需要对 String
类进行扩展。这是假设您总是在字符串上调用方法。从您的代码来看,它是正确的。这是一个例子:
lib/core_ext/string.rb
class String
def nicename
# all entries in the DB are in lower case and need to be formated
# for dislay in views:
self.gsub(/[\s]/,'-').split("-").map {|m|m.capitalize}.join('-')
end
end
确保重新加载您的服务器并检查类是否已加载。希望它能满足您的需求。
关于ruby-on-rails - 格式化 helper_methods 以便在 View 中使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42066764/