ruby on rails uses too much memory on undefined method - ruby-on-rails

I have a problem on my ruby on rails application. It uses too much memory whenever it encounters an undefined method. It freezes the server until I kill the process. Error log points to the undefined method that goes to something like this:
ActionView::Template::Error (undefined method `testos' for #<#:0x007fb3d88de8c8>):
Is there any way or configuration to fix this? I am using ruby 1.9.3 on rails 3.2.2.
Here is the stack trace
Completed 500 Internal Server Error in 53960ms
ActionView::Template::Error (undefined method testos' for #<#<Class:0x007fb3d43d0420>:0x007fb3d479c8d8>):
77: #rules["data"].each do |rule|
78: json_rule =ActiveSupport::JSON.decode(rule["json_rule"])
79: %>
80: <%=testos(1)%>
81: <div class="dvGridRow" style="width:100%;padding-bottom:10px;">
82: <div class="dvGridData" style="vertical-align:top;width:190px;margin-left:5px;">
83: <%= json_rule["rule_name"]%>
app/views/rules/index.html.erb:80:inblock in _app_views_rules_index_html_erb_4146358986539966513_70205169705180'
app/views/rules/index.html.erb:77:in each'
app/views/rules/index.html.erb:77:in
_app_views_rules_index_html_erb_4146358986539966513_70205169705180'
Rendered /Users/jay/.rvm/gems/ruby-1.9.3-p194/gems/actionpack-3.2.2/lib/action_dispatch/middleware/templates/rescues/_trace.erb (6.4ms)
cache: [GET /manage/rules] miss
Rendered /Users/jay/.rvm/gems/ruby-1.9.3-p194/gems/actionpack-3.2.2/lib/action_dispatch/middleware/templates/rescues/_request_and_response.erb (1.8ms)
Rendered /Users/jay/.rvm/gems/ruby-1.9.3-p194/gems/actionpack-3.2.2/lib/action_dispatch/middleware/templates/rescues/template_error.erb within rescues/layout (18.5ms)
note:
I intentionally called an unidentified method, because I am trying to figure out where does my code freezes the machine, and that error causes it.
Thanks

A Problem (and a Solution)
Let’s say your working with a Ruby object. And let’s also say that you aren’t entirely familiar with this object. And let’s also say that you call a method that doesn’t exist on the object.
o = Object.new
o.some_method
NoMethodError: undefined method `some_method' for #
This is less than desirable, so Ruby has an awesome way of allowing us to rescue ourselves from this. Check this out:
class OurClass
def method_missing (method_name)
puts "there's no method called '#{method_name}'"
end
end
o = OurClass.new
o.some_method
=> there's no method called 'some_method'
We can create a method called method_missing in our class. If the object we’re calling the method on doesn’t have the method (and doesn’t inherit the method from another class or module), Ruby will give us one more chance to do something useful: if the class has a method_missing method, we’ll hand the information about the method cal to method_missing and let it sort the mess out.
Well, that’s great; we’re no longer getting an error message.
reference from this link
http://net.tutsplus.com/tutorials/ruby/ruby-for-newbies-missing-methods/

Related

NoMethodError in controller that has methods defined

I finished implementing and testing a controller, then switched back and forth between Git branches and did some merges here and there, etc.
Now I'm unable to use the methods I've defined for the controller, and also very confused, as I'm getting NoMethodError when trying to call them.
Added an edit and solution at the end of the post.
Using Rails version 5.2.3 -
Here I've got my controller defined: app/controllers/paypal_access_token_controller.rb:
class PaypalAccessTokenController < ApplicationController
before_action :authenticate_admin!, only: [:show]
def njurf
puts "#######################"
puts "why can't i call these methods dangit"
puts "#######################"
end
def show
# doesn't really matter
end
def update
# doesn't really matter either
# no syntax errors, I promise
end
end
I'd like the update method to be called when I start the Rails application.
I added PaypalAccessToken.update() to the file config/environments/development.rb - this worked.
Now that I've implemented stuff in other seemingly unrelated parts of the application, I can't call on methods from this controller anymore.
I removed the line from config/environments/development.rb so that I could run the Rails console and added the njurf method to the controller. From the console, I tried calling PaypalAccessTokenController.njurf, and PaypalAccessTokenController.update, but both give me the bespoke NoMethodError.
Here's some proof of concept
Loading development environment (Rails 5.2.3)
irb(main):001:0> PaypalAccessTokenController.update
Traceback (most recent call last):
1: from (irb):1
NoMethodError (undefined method `update' for PaypalAccessTokenController:Class)
irb(main):002:0> PaypalAccessTokenController.update()
Traceback (most recent call last):
1: from (irb):2
NoMethodError (undefined method `update' for PaypalAccessTokenController:Class)
irb(main):003:0> PaypalAccessTokenController.njurf()
Traceback (most recent call last):
1: from (irb):3
NoMethodError (undefined method `njurf' for PaypalAccessTokenController:Class)
So the controller class exists, at least, but I don't know why I'm getting this error - nor do I know how to go about fixing it.
Any help would be appreciated.
edit: This controller only had routes for the show method. I removed this route when I had implemented and tested the update method, because I no longer needed/wanted these methods to be accessible via URLs.
This is what made the methods inaccessible from console.
solution: Either I leave in a route to one of the controller's methods - or, like Ricky Spanish and amit_saxena pointed out below, properly declare the methods as class methods.
Thanks for the replies
You can call it, when you define it with self
def self.njurf
puts "#######################"
puts "why can't i call these methods dangit"
puts "#######################"
end
PaypalAccessTokenController.njurf
#######################
why can't i call these methods dangit
#######################
=> nil
It might look strange, but are you sure you have defined the proper resources on routes?
You cannot access controller methods like that from console as they aren't class methods. You can instead try this:
PaypalAccessTokenController.new.update
but that doesn't mean it's going to work (it probably needs params to work on), but you will not get a NoMethodError. Most probably you messed something in your routes file. You can check the routes using:
bundle exec rake routes
which will tell you exactly which route points to which controller#action and should give you some pointers about what the problem is. Paste the relevant routes here is you are unable to figure it out. Also pay attention to HTTP method (GET/POST/PATCH). You might be using a GET instead of PATCH and getting the error as a result.

Heroku Array Unshift Method Rails

I have a working rails app on my local machine. I updated my Heroku and started to test it. One of my views requires the controller to add elements to an array using unshift.
When I go to this view on the web, I get an error We're sorry, but something went wrong.
I went into $heroku logs and the most recent errors are:
2014-02-28T02:08:26.650021+00:00 app[web.1]: NoMethodError (undefined method `unshift' for #<ActiveRecord::AttributeMethods::Serialization::Attribute:0x007fe57862f588>):
2014-02-28T02:08:26.650021+00:00 app[web.1]: app/controllers/users_controller.rb:32:in `show'
Any ideas how to fix this?
my controller function looks like this:
#user.daily = #user.daily.unshift(day)
#user.daily is a serialized array
#Mhsmith21, if day is an object and if you are rails 4+ then my suggestion is to use build instead of unshift.
If you are using unshift to add the object on first position then use build and reverse the array.
As unshift does not work for ActiveRecord::Associations::CollectionProxy.

Using find_by_<field> returns "Table doesn't exist" error

I'm working on a Ruby 1.8 / Rails 2.1 application which is connecting to a SQL Server 2008 database.
When I try to use a find_by_CompanyCode method, ActiveRecord returns a NoMethodError. Yet, from the following you can see that the table exists and has the method in question.
Not sure what I'm missing.. any help would be appreciated
EDIT: Only fields which end in "Code" aren't appearing when I just run IvantageEmployee.first .. error occurs from a view. Moving the exact same code to a controller, the code works as expected.
eval #goal.organization_type.employee_class + ".find_by_#{#goal.organization_type.employee_field_code}('#{#goal.specifier}').#{#goal.organization_type.employee_field_description}"
>> IvantageEmployee.first.CompanyCode
=> "GAI"
>> IvantageEmployee.find_by_CompanyCode('GAI')
NoMethodError: undefined method `find_by_CompanyCode' for IvantageEmployee(Table doesn't exist):Class
from /usr/lib/ruby/gems/1.8/gems/activerecord-2.1.0/lib/active_record/base.rb:1613:in `method_missing_without_paginate'
from /usr/lib/ruby/gems/1.8/gems/will_paginate-2.3.15/lib/will_paginate/finder.rb:170:in `method_missing'
from (irb):7
>>
Some more information. The table has several fields. The one I'm struggling with is CompanyCode, but it also has RegionDescription.
Note the following console output. find_by_RegionDescription works; find_by_CompanyCode doesn't work. Also, CompanyCode doesn't appear when I just output the class, but RegionDescription doesn't Not sure why ActiveRecord would be missing fields that are on the table
>> IvantageEmployee.find_by_RegionDescription 'GAI'
### Finding method find_by_RegionDescription
=> nil
>> IvantageEmployee.find_by_CompanyCode 'GAI'
### Finding method find_by_CompanyCode
NoMethodError: undefined method `find_by_CompanyCode' for IvantageEmployee(Table doesn't exist):Class
from /usr/lib/ruby/gems/1.8/gems/activerecord-2.1.0/lib/active_record/base.rb:1614:in `method_missing_without_paginate'
from /usr/lib/ruby/gems/1.8/gems/will_paginate-2.3.15/lib/will_paginate/finder.rb:170:in `method_missing'
from (irb):9
>>
You need to use snake case instead of camel case:
IvantageEmployee.find_by_company_code('GAI')
The convention in ruby is to use camel case for classes and snake case for methods. Rails follows that convention(as should you) so you can assume that any methods dynamically created by it are going to be snake case.

What are reasons "reload!" doesn't always seem to work in the Rails console?

I'm just getting the hang of Rails console, and finding it useful for quickly testing methods in my classes. I know that I can make changes to my Models, then
> reload!
to grab those updates, but sometimes I'll find that it doesn't seem to reload my latest code. Does Rails cache code somewhere?
In a really simple pseudo example, I may have bad code on line 100:
100: u = User.alll
and in the Rails console, when I run this method, I might get an error similar to:
NoMethodError: undefined method `alll' for User:Class ... on line 100
then modify my code, fixing the error
100: u = User.all
then reload:
> reload!
and then, when calling the method in this class that has the correct code, it still will say
NoMethodError: undefined method `alll' for User:Class ... on line 100
When clearly, the error is fixed, and the offending line isn't even on line 100 anymore. Is there a way to force/hard-reset the "reload!" command?
My guess would be that you're doing something like:
Create an instance of User
Call someMethod on the instance
You get an error, and you go and fix it
reload!
You call someMethod on the existing instance and get the error again
So you're calling the method on an instance that hasn't itself been reloaded. Its class has been reloaded, but the instance is already in memory - with bugs and all.
That would be my guess at least (not 100% sure).
Point is, if you create a new instance after the reload! and call your method on that new instance, it should stop complaining.

NoMethodError in rails

The extracted source is below :
Showing /usr/lib/ruby/gems/1.8/gems/actionpack-2.3.5/lib/action_controller/templates/rescues/diagnostics.erb where line # raised:
private method `gsub' called for #<NoMethodError: undefined method `closed?' for nil:NilClass>
Extracted source (around line #):
RAILS_ROOT: /home/sharath/Desktop/RORWorkspace/ITPLOW1
It was working before installing Sunspot: A Solr-Powered Search Engine for Ruby.
I am working in Ubuntu 10.04.
I'd need to see the full stacktrace to be sure, but this is actually probably an unhelpful HTTP connection error message bubbling up out of RSolr (the library the Sunspot uses for the low-level Solr connection). Is Solr running (i.e., did you run rake sunspot:solr:start)? Can you access http://localhost:8982/solr/admin ?
What's probably happening is you're attempting to do a substitution on some variable which you thought you were initializing, but neglected to give a real value.
For instance, if you had a form where for a Message and one of the the properties you want is the content, you would normally retrieve that information in the controller with
params[:message][:content]
And if you wanted to filter it, you would do something like
params[:message][:content].gsub(/<[^>]*>/,"")
But if the user didn't enter anything into the content field, the params[:message][:content] variable wouldn't be set. Therefore it's null and you're attempting to do nil.gsub

Resources