我正在尝试使用感性的宝石来对推文进行基本的情绪分析。我已经在初始化文件中实例化了Sentimental,并尝试在推文的文本上调用该函数,但却得到了错误:
undefined method `sentiment' for nil:NilClass
指的是这一行:
<%= $analyzer.sentiment(t.text) %>
初始化/ sentimental.rb
$analyzer = Sentimental.new
$analyzer.load_defaults
home.html.erb
<ul>
<% query = params["q"] %>
<% if query != nil and query.chars.include? "#" %>
<% TwitterApi.search_twitter(query).each do |t| %>
<% tweet = TwitterApi.embed(t)%>
<%= raw(tweet.html) %>
<%= $analyzer.sentiment(t.text)%>
<li><%= t.text %></li>
<% end %>
<% end %>
</ul>
答案 0 :(得分:0)
我认为这个例子可以解决这个问题:
# controller
before_action :set_analyzer, only: [:needed_action]
# ... some code
def set_analyzer
@analyzer ||= Sentimental.new
@analyzer.load_defaults
end
# home.html.erb
<ul>
<% query = params["q"] %>
<% if query != nil and query.chars.include? "#" %>
<% TwitterApi.search_twitter(query).each do |t| %>
<% tweet = TwitterApi.embed(t)%>
<%= raw(tweet.html) %>
<%= @analyzer.sentiment(t.text)%>
<li><%= t.text %></li>
<% end %>
<% end %>
</ul>
答案 1 :(得分:0)
您的全局变量未设置,这很奇怪。您确定在此之后重新启动了服务器吗?
如果仍然不起作用,我认为这可能是一种方法:
#use a constant in your initializer
SentimentAnalyzer = Sentimental.new
SentimentAnalyzer.load_defaults