How to inherit from NilClass or how to simulate similar function
An approach that may work for you is to overide the method #nil? in your Null object.
This means that in your code to test for null you have to use obj.nil? and not just check for obj existence. This is probably reasonable, since you can distinguish between nil and null. Below is an example:
class NullClass
def nil?
true
end
def null_behavior
puts "Hello from null land"
end
end
Inheritance will work:
class NewClass < NullClass
end
Use like so:
normal = Class.new
null = NewClass.new
x = [normal, null]
x.each do |obj|
if obj.nil?
puts "obj is nil"
obj.null_behavior
end
end
Output:
obj is nil
Hello from null land
Just remember to use #.nil? for any checks that require Null and Nil to be false-ish.
Below this line was my WRONG initial answer
CustomNil = Class.new(NilClass)
class CustomNil
def self.new
###!!! This returns regular nil, not anything special.
end
end
[tests deleted for brevity]
Use at your own risk. I haven't researched what side effects this may cause or whether it will do what you want. But it seems it does have some nil like behavior
How do I create a class which instance can be evaluated as false?
Boolean logic in Ruby ONLY allows nil
and false
to be falsy
Everything else is truthy
.
There is no way to do this.
May I ask why you want this?
What is special about your Nilly
class?
I suggest you just call it a different way.
class Nilly
def nil?
true
end
end
And use this in your logic
puts n.nil? ? 'false' : 'true'
Rails undefined method `[]' for nil:NilClass
Try this
def initialize
super
@session_types = Array.new
@program_id = ''
end
You were very scarce with pasting your errors, but that's the first thing that comes to mind. Please post the entire error if this doesn't help.
The reason for that is your Setting
class inherits from ActiveRecord::Base
, calling super
first calls parent's initialize
method, this way you add functionality to the method (extend it). Without super
you override it, meaning you replace everything it does by default (like for example connecting to the database, validating) by your code.
NilClass - What does Ruby inheritance really mean?
I assumed that "inheritance" is the basic feature of Ruby. And every class inherits methods from both its
.class
and.superclass
.
That's correct. Every class inherits methods from its superclass, which is Object
by default.
class Foo
end
Foo.superclass #=> Object
Foo
responds to Object
's class methods and Foo
instances respond to Object
's instance methods.
Furthermore, every class is an instance of Class
and therefore responds to Class
' instance methods (just like Foo
instances respond to Foo
's instance methods):
Foo.class #=> Class
Foo.method(:new)
#=> #<Method: Class#new>
Calling Foo.new
simply invokes Class#new
.
Since
NilClass
hasClass
andObject
as its.class
and.superclass
, you'd assumeNilClass
to have all their methods.
It would, but nil
is a singleton, i.e. there's only one nil
instance and you can't create any other instances. This is achieved (among other things) by undefining new
. From Ruby's source code:
rb_undef_method(CLASS_OF(rb_cNilClass), "new");
You could do the same in plain Ruby:
Foo.singleton_class.send(:undef_method, :new)
Foo.new
#=> NoMethodError: undefined method `new' for Foo:Class
self join association undefined method for nil:NilClass
It turns out that despite calling reload, Rails still uses the cached version of the query. The same problem is described here. This fixes it:
class ItemA < Item
def parent
ActiveRecord::Base.uncached { groups.take }
end
end
NoMethodError undefined method `[]=' for nil:NilClass
The problem is when you initialize your @query_hash
. In all your classes they are initialized in wrong scope. To fix it, you should move @query_hash = Hash.new
to initialize
method, like:
class RangeCriteria
def initialize
@query_hash = Hash.new
end
# ...
end
class RangeBuilder
def initialize
@query_hash = Hash.new
end
# ...
end
class Bool
def initialize
@query_hash = Hash.new
end
# ...
end
Hope that helps.
Good luck!
undefined method `[]' for nil:NilClass for Rails model on new
You're breaking things with t.string :class
@student.class
needs to return Student
for ActiveRecord to do its magic.
Your @student.class
is going to return nil
. That's a problem.
undefined method `articles' for nil:NilClass when i tried to display related articles on my article show page
Here is a longer answer that offers a solution to your problem. The issue is that you want to get all articles
that share a tag
with the article
you are showing, while presumably not showing the current article in the list of related articles. I would accomplish this by adding a related_articles
method to your Article
model and calling it in your view.
Add the following method to app/models/article.rb
:
def related_articles
Article.joins(:tags).where(tags: { id: self.tags.pluck(:id) }).where.not(id: self.id)
end
The above query should return all of the articles that have a matching tag while excluding itself.
You can now replace the related articles section in your view with:
**<h5>Related Articles</h5>
<% @article.related_articles.each do |article| %>
<li><%= link_to article.title, article_path(article) %></li>
<% end %>**
One final note that is not strictly related to your problem, but worth mentioning. By iterating over @article.tags
, your view is creating an N+1 query. These are very inefficient. The good news, is that this can be fixed with eager loading by simply, changing the find_articles
method in your articles_controller
as follows:
def find_article
@article = Article.includes(:tags).find(params[:id])
end
There may be a more efficient way to write the related_articles
query, but this should work.
EDIT:
Another way of writing the related_articles
query follows. This will yield the same results. It moves more of the processing to the database and results in fewer calls to the database.
def related_articles
Article.distinct.joins(tags: :articles).where.not(id: self.id)
end
Undefined method 'accept' for nil:NilClass after upgrading to Rails 3
Figured it out. Turns out a custom gem someone made a long time ago caused some errors. Removing that gem fixed it.
For those who have a similar problem, ensure you remove the 'activerecord-mysql2-adapter' gem. That was what caused the initial problem.
Related Topics
Creating a Test Suite Using Ruby Minitest
Initialize a Ruby Class from an Arbitrary Hash, But Only Keys with Matching Accessors
Ruby -V Dyld: Library Not Loaded: /Usr/Local/Lib/Libgmp.10.Dylib
Write Array of Radix-2 Numeric Strings to Binary File in Ruby
Rails -V Cannot Load Such File -- Rails/Cli (Loaderror)
Why Do Ruby Procs/Blocks with Splat Arguments Behave Differently Than Methods and Lambdas
Kill Process and Sub-Processes in Ruby on Windows
Clicking Link with JavaScript in Mechanize
What Are the Differences Between Lazy, Greedy and Possessive Quantifiers
Problems Keeping an Object in an Array, Ruby Issues and Rails Issues
In Ruby How to Automatically Populate Instance Variables Somehow in the Initialize Method
How to Add a Custom Log Level to Logger in Ruby
Ruby: Escaping Special Characters in a String
Heroku: How to Push to Specific App If You Have Multiple Apps in Heroku
Troubles with Ruby-2.X Installation Using Rvm