I'm learning how to use Sinatra. I figured out that when I pass object as locals, e.g.:
product = FetchProduct.new.call(id) #function finds exact Product instance
erb :"products/show", locals: { product: product }
I can use product object in my views with all instance methods I declared. But I can't use any class method, any attempt to do so gives me uninitialized constant error. What should I do if I want to use Product.format_price(product.price)
method? Is there any way to pass class methods to Sinatra views?
答案 0 :(得分:1)
klass = const_get( product.class )
klass.format_price
But that doesn't really make sense because you already know you want Product.format_price
. So why don't you use Product.format_price
?
答案 1 :(得分:0)
在你的观点中运行这种逻辑通常是一个坏主意。最佳做法是尽可能满足其需要。
请注意您在视图中运行类方法的原因是因为您的视图中无法访问Product
,而且说实话,如果您想关注,则不应该如此MVC原则。
如果它只是视图中您需要的format_price
方法(特别是因为您似乎将Product
的实例传递给Product.format_price
这很奇怪而且大代码嗅觉),然后创建一个名为format_price
的辅助方法,可以被视图访问,或者更好的是,在控制器中创建一个名为format_price
的辅助方法(或者包含在你的辅助模块中)控制器)并将返回值作为本地传递
get '/' do
product = FetchProduct.new.call(id)
erb :'products/show', locals: {
product: product,
price: format_price(product)
}
end
private
def format_price(product)
# awesome formatting logic
end