Rails 3.2
I've used logger.info successfully in the past. Today, I was trying to debug a model's action, and it's breaking my application. My code (in models/admin_ability.rb):
can :decline, Ticket do |ticket|
if ticket.persisted?
logger.info("File: #{__FILE__ } -- LINE: #{__LINE__ }")
executor = ticket.executor
ticket_profile = ticket.ticket_profile
decliners = ticket.decliners
suitable_companies = ''
suitable_companies = ticket_profile.suitable_companies(decliners, ticket.customer, ticket.customer_info.zip, ticket.requested_date_start,
false, false) if decliners.blank?
suitable_companies.delete(ticket.executor)
!(suitable_companies.compact).blank?
end
end
Here's the error message:
undefined local variable or method `logger' for #<AdminAbility:0x007f8382bfd3f0>
Rails.root: /home/app
Application Trace | Framework Trace | Full Trace
app/models/admin_ability.rb:40:in `block in initialize'
Line 40 is:
logger.info("File: #{__FILE__ } -- LINE: #{__LINE__ }")
Any ideas?
Call logger on the Rails constant: Rails.logger.info
Related
I don't know that much about RUBY, just thought that you guys might help me with this. I'm using Storyblok as my headless CMS and JEKYLL when I'm building serve it this is the error that I got;
33: from C:/project/test/_plugins/storyblok_generator.rb:8:in `generate'
32: from C:/project/test/_plugins/storyblok_cms/generator.rb:12:in `generate!'
C:/project/test/vendor/cache/ruby/2.7.0/gems/storyblok-3.0.1/lib/storyblok/client.rb:354:in `block (2 levels) in find_and_fill_links': undefined method `[]' for nil:NilClass (NoMethodError)
the code below is from _plugins/storyblok_cms/generator.rb
def generate!
timestamp = Time.now.to_i
links = client.links(cv: timestamp)['data']['links']
stories = client.stories(per_page: 100, page: 1, cv: timestamp)['data']['stories'] #line 12
stories.each do |story|
# create all pages except global (header,footer,etc.)
content_type = story['content']['component']
if content_type != 'shared'
site.pages << create_page(site, story, links)
end
rescue UnknownContentTypeError => e
# for production, raise unknown content type error;
# for preview and other environments, issue an warning only since the content_type might be available
# but the code handling that content type might be in a different branch.
Jekyll.env == 'production' ? raise : Jekyll.logger.warn(e.message)
end
site.data['stories'] = stories
site.data['articles'] = stories.select { |story| story['full_slug'].start_with?('articles') }
site.data['shared'] = stories.select { |story| story['full_slug'].start_with?('shared') }
end
the code below is from _plugins/storyblok_generator.rb
require "storyblok"
module Jekyll
class StoryblokGenerator < Jekyll::Generator
safe true
def generate(site)
StoryblokCms::Generator.new(site).generate! #line 8
end
end
end
Additional Info:
ruby version: ruby 2.7.4p191 (2021-07-07 revision a21a3b7d23) [x64-mingw32]
jekyll version: jekyll 4.2.1
OS: Windows 10
I've actually found the solution to this, So this error occurs because I have created a page template in Block Library in Storyblok and then firing bundle exec jekyll serve command in terminal without creating the page template source/file in my project directory.
So I have an about_us block (content-type) in Block Library created and then when I fire bundle exec jekyll serve without creating an about_us.html first in _layouts folder, It would trigger the error.
Solution;
Make sure to create the source/file first in the _layouts folder if you have created a block (content-type) in block library.
I'm stumped.
I inherited a Rails 2.X app upgraded to a Rails 3.1 app and I'm getting this weird error...
NoMethodError - undefined method `rescue_action_locally' for #<AssignmentsController:0x000000042583d0>:
app/controllers/application_controller.rb:362:in `process_exception'
And error output is pointing me to line 362 ...
def process_exception(exception)
authorize
set_cashier
if rescue_as_normal
ret = rescue_action(exception)
else
ret = rescue_action_locally(exception) <--- but why is this exploding?
end
if request and request.xhr?
response.content_type = Mime::JS
end
return ret
end
I'm on rbenv and my ruby is 1.9.3-p551
If I function-click this in Rubymine I can see this exist inside action_dispatch/middleware/show_exeptions.rb:80 ... So I know the thing is there.
I have no idea why this is exploding. Any clues appreciated.
I am using Ruby on Rails. I am trying to implement https://www.kraken.com/help/api
Incase it isn't obvious, my knowledge of implementing API's and gems is very basic.
I go to the "example-api-code" paragraph and I get to https://github.com/leishman/kraken_ruby
I include the gem and do the bundle.
Now we get to "Usage" "Create A Client"
I assume I put the following in config/kraken.rb
API_KEY = '3bH+M/nLp......'
API_SECRET = 'wQG+7Lr9b.....'
kraken = Kraken::Client.new(API_KEY, API_SECRET)
time = kraken.server_time
time.unixtime #=> 1393056191
I wanted to test something simple, such as displaying the time.
I put the following code in my views/welcome/index.html.erb file, but then I get an error.
<p><%= kraken.server_time %></p>
-> ActionView::Template::Error (undefined local variable or method `kraken' for #<#<Class:0x007f95c6246ba8>:0x007f95c6245eb0>):
Trying this code in my html.erb file and it gives me another error
<p><%= #kraken.server_time %></p>
-> ActionView::Template::Error (undefined method `server_time' for nil:NilClass):
-------------------------------------------------------------------------------
EDIT: Solutions Attempts, TLDR NameError (uninitialized constant...
# Gladis
Using your solution I get this error
->! Unable to load application: SyntaxError: /app/app/controllers/welcome_controller.rb:5: dynamic constant assignment
-> API_KEY = '...'
So I tried
def index
#kraken = Kraken::Client.new('3bH+M/nLp...', 'wQG+7Lr9b...')
time = #kraken.server_time
time.unixtime #=> 1393056191
end
and got this new error
NameError (uninitialized constant WelcomeController::Kraken):
app/controllers/welcome_controller.rb:5:in `index'
# Pavel Tkackenko
Your first solution (wrapping in singleton-like class) gives me this error.
ActionView::Template::Error (uninitialized constant ActionView::CompiledTemplates::KrakenClient):
app/views/welcome/index.html.erb:1:in `_app_views_welcome_index_html_erb__3584347874708863751_70226442404480'
1: <p><%= KrakenClient.get.server_time %></p>
Your second solutions (monkey-patch) gives me the this error.
ActionView::Template::Error (uninitialized constant ActionView::CompiledTemplates::Kraken):
1: <p><%= Kraken.client.server_time %></p>
app/views/welcome/index.html.erb:1:in `_app_views_welcome_index_html_erb___3719740865851336982_69820265644620'
Moving /config/kraken.rb to /config/initializers/kraken.rb using Pavel's method
Wrapping it in singleton-like class gives me this error (infact, it doesn't even let me host the server)
->When I host it on my local computer with bin/rails server
/config/initializers/kraken.rb:6:in `<class:KrakenClient>': uninitialized constant KrakenClient::Kraken (NameError)
/config/initializers/kraken.rb:1:in `<top (required)>'
->When I host it on heroku
Running: rake assets:precompile
rake aborted!
NameError: uninitialized constant KrakenClient::Kraken
/config/initializers/kraken.rb:5:in `<class:KrakenClient>'
/config/initializers/kraken.rb:1:in `<top (required)>'
...
/config/environment.rb:5:in `<top (required)>'
With monkey-patch I get this error
ActionView::Template::Error (uninitialized constant Kraken::Client):
1: <p><%= Kraken.client.server_time %></p>
config/initializers/kraken.rb:8:in `client'
app/views/welcome/index.html.erb:1:in `_app_views_welcome_index_html_erb___577296263292451462_70097201303100'
If you got it to work on your computer, I would be happy to use your code as a skeleton (I am assuming this will be easier than figuring out what's wrong on my side).
Put this code in WelcomeController.rb
def index
API_KEY = '3bH+M/nLp......'
API_SECRET = 'wQG+7Lr9b.....'
#kraken = Kraken::Client.new(API_KEY, API_SECRET)
time = #kraken.server_time
time.unixtime #=> 1393056191
end
In view under this controller put:
<p><%= #kraken.server_time %></p>
kraken = Kraken::Client.new(API_KEY, API_SECRET)
kraken here is local variable. If you put it into config/kraken.rb, it will not be accessible outside.
There are different solutions. One is to wrap it in singleton-like class:
# config/initializers/kraken.rb
class KrakenClient
API_KEY = '3bH+M/nLp......'
API_SECRET = 'wQG+7Lr9b.....'
##config = Kraken::Client.new(API_KEY, API_SECRET)
def self.get
##config
end
end
# index.html.erb
<p><%= KrakenClient.get.server_time %></p>
Another one approach is to monkey-patch Kraken itself:
# config/initializers/kraken.rb
class Kraken
API_KEY = '3bH+M/nLp......'
API_SECRET = 'wQG+7Lr9b.....'
class << self
def client
#client ||= Kraken::Client.new(API_KEY, API_SECRET)
end
end
end
# index.html.erb
<p><%= Kraken.client.server_time %></p>
Recently, we found that when running certain reports (Either Project Status or Requirement Coverage) the report fails with a popup showing:
undefined method `[]' for nil:NilClass
Examining the httpd access logs I see the following:
"GET /report/requirement_coverage/?sort_by=id&test_object_ids=12 HTTP/1.1" 403 38 "http://tarantula.xxxxx.xxxx/"
in the production.log file, we also see this:
undefined method []' for nil:NilClass
/opt/tarantula/rails/lib/priority_extensions.rb:9:inpriority_name'
/opt/tarantula/rails/app/models/report/requirement_coverage.rb:115:in case_info'
/opt/tarantula/rails/app/models/report/requirement_coverage.rb:77:inblock (2 levels) in do_query'
/opt/tarantula/rails/vendor/bundle/ruby/1.9.1/gems/activerecord-3.2.18/lib/active_record/associations/collection_proxy.rb:91:in each'
/opt/tarantula/rails/vendor/bundle/ruby/1.9.1/gems/activerecord-3.2.18/lib/active_record/associations/collection_proxy.rb:91:inmethod_missing'
/opt/tarantula/rails/app/models/report/requirement_coverage.rb:77:in block in do_query'
/opt/tarantula/rails/vendor/bundle/ruby/1.9.1/gems/activerecord-3.2.18/lib/active_record/relation/delegation.rb:6:ineach'
/opt/tarantula/rails/vendor/bundle/ruby/1.9.1/gems/activerecord-3.2.18/lib/active_record/relation/delegation.rb:6:in each'
/opt/tarantula/rails/app/models/report/requirement_coverage.rb:66:indo_query'
lots more under this followd by:
/opt/tarantula/rails/vendor/bundle/ruby/1.9.1/gems/passenger-3.0.19/helper-scripts/passenger-spawn-server:99:in `'
Completed 403 Forbidden in 113381.4ms (Views: 0.2ms | ActiveRecord: 7849.2ms)
NOTE: this is not my code, but code from a module of Testia Tarantula
=begin rdoc
Include this in a model which is to be prioritized.
=end
module PriorityExtensions
def priority_name
Project::Priorities.detect{|p| p[:value] == self.priority}[:name]
end
def priority=(p)
if p.is_a? String
p_val = Project::Priorities.detect{|pp| pp[:name] == p.downcase}
if p_val
self[:priority] = p_val[:value]
else
raise "Invalid priority '#{p}' for #{self.class} (id #{self.id})"
end
else
self[:priority] = p
end
end
def self.included(model)
model.validates_inclusion_of :priority, :in => Project::Priorities.map{|p| p[:value]}
end
end
Found the issue, a column "priority" in the table "cases", had somehow been changed to an invalid NULL. Changing the value to '0' (normal) fixed the issue.
I am a beginner programmer in Ruby and Ruby on Rails , I'm trying to run a rake command in my task , but when I do the following happens:
rake daily_tasks:process_api
rake aborted!
ActiveRecord::AssociationTypeMismatch: Estado(#47392639701120) expected, got NilClass(#47392580444120)
/home/thiagoamaralr/Desktop/proponente-master-4f8a3b2ddb02a90b2c173cf31383505018d02dd/app/services/create_programa_api.rb:21:in `call'
/home/thiagoamaralr/Desktop/proponente-master-74f8a3b2ddb02a90b2c173cf31383505018d02dd/lib/tasks/daily_tasks.rake:7:in `block (3 levels) in <top (required)>'
/home/thiagoamaralr/Desktop/proponente-master-74f8a3b2ddb02a90b2c173cf31383505018d02dd/lib/tasks/daily_tasks.rake:5:in `each'
/home/thiagoamaralr/Desktop/proponente-master-74f8a3b2ddb02a90b2c173cf31383505018d02dd/lib/tasks/daily_tasks.rake:5:in `block (2 levels) in <top (required)>'
Tasks: TOP => daily_tasks:process_api
(See full trace by running task with --trace)
Follow the task I'm trying to run:
namespace :daily_tasks do
desc "Process the day to day tasks"
task process_api: :environment do
SiconvApi::Programa.find.each do |programa|
if programa.data_inicio_recebimento_propostas && (programa.data_inicio_recebimento_propostas.to_date >= Date.parse("2015/06/01"))
CreateProgramaApi.call(SiconvApi::Serializers::Programa.new(programa))
end
end
end
end
And this is content create_programa_api.rb:
class CreateProgramaApi
def self.call(programa_api)
params = programa_api.to_h
params[:orgao] = Orgao.where("lower(name) = ?", programa_api[:orgao][:nome].mb_chars.downcase).first_or_create(name: programa_api[:orgao][:nome])
params[:orgao_vinculado] = Orgao.where("lower(name) = ?", programa_api[:orgao_vinculado][:nome].mb_chars.downcase).first_or_create(name: programa_api[:orgao_vinculado][:nome])
params[:orgao_executor] = Orgao.where("lower(name) = ?", programa_api[:orgao_executor][:nome].mb_chars.downcase).first_or_create(name: programa_api[:orgao_executor][:nome])
params[:estados] = []
if programa_api[:estados].size == 27
params[:estados] << Estado.find_by(sigla: 'Todos')
else
programa_api[:estados].each do |e|
params[:estados] << Estado.find_by(sigla: e)
end
end
params[:atendes] = [Atende.where("lower(name) = ?", programa_api[:atende_a].mb_chars.downcase).first_or_create(name: programa_api[:atende_a])] if programa_api[:atende_a]
params.delete(:atende_a)
programa = Programa.find_by(codigo: programa_api[:codigo])
if programa
programa.update(params)
else
Programa.create! params
end
end
end
Thanks for your attention!
You have nil object in params[:estados], and Rails can't save this association.
Easiest way to remove them is to call params[:estados].compact! after line 14
This block of code is your problem:
params[:estados] = []
if programa_api[:estados].size == 27
params[:estados] << Estado.find_by(sigla: 'Todos')
else
programa_api[:estados].each do |e|
params[:estados] << Estado.find_by(sigla: e)
end
end
If no record is found, the #find_by returns nil. This is why you are getting the error:
ActiveRecord::AssociationTypeMismatch: Estado(#47392639701120) expected, got NilClass
When calling Programa.create!(params).
One solution would be to call params[:estados].compact! after the if statement (this is using Array#compact! to remove any nil values).
Or, you could instead write that section of code like this:
params[:estados] = Estadio.where(
sigla: (programa_api[:estados].size == 27 ? 'Todos' : programa_api[:estados])
)
With this code, there is no longer a need to call compact! since we already end up with an empty array if no records are found (i.e. there are no nil values).
Note that the behaviour here isn't quite the same - what happens if there are multiple Estado records with the sigla equal to one of programa_api[:estados] or 'Todos'? Previously you were only fetching the "first" such record, whereas now you'd be fetching all of them. This may not be an issue (or may even be the correct behaviour!!) - it's just something to be aware of, at least.