Rails If Object.Nil? Then Magic '' in Views

rails if object.nil? then magic '' in views?

What about:

<%= tax_payment.user.name if tax_payment.user %>

Ruby: if !object.nil? or if object

There are differences. For example:

false.nil?
# => false

So:

if !false.nil?
'foo'
end
# => "foo"

if false
'foo'
end
# => nil

As @tokland suggested, in most cases using !obj.nil? construction is unnecessary.

Confused about nil rails view

You want to check and make sure that profile.listings is not blank or empty. If you call the last method on an empty array, it returns nil.

<% if profile.listings %> will return true even if you have an empty array.

<% if !profile.listings.blank? %> or <% unless profile.listings.blank? %> should do the trick.

What is the best practice for handling nil objects and properties?

I like to use the Null Object Pattern. Avdi has a great post explaining this, but the basic idea is you have a little class that can stand in for an object and respond reasonably to the messages you might pass the original object. I've found these are useful not only for avoiding NoMethodErrors but also for setting default values/nice messages.

For instance, you could do:

class NilUser
def email
"(no email address)"
end
end

u = User.find(1) || NilUser.new
u.email.upcase.last # => No errors!

Rails Model method check if field nil, if so return empty string

You can, although this might not be what you wanted, simply remove any nil objects from the address Array using the #compact method, so that #empty? will work...:

def full_address
[self.address1, self.address2, self.address3,
self.city, self.state, self.zipcode].compact.reject!(&:empty?).join(', ')
end

You should be aware that this WILL return a partial address if SOME of the fields exist.

I would probably void any fault addresses (in this example I require just the first address line and the city fields):

def full_address
return "" unless self.address1 && self.city && !self.address1.empty? && !self.city.empty?
[self.address1, self.address2, self.address3,
self.city, self.state, self.zipcode].compact.reject!(&:empty?).join(', ')
end

Disregarding the few edits I made to the code, I would probably go with @Joseph's #present? together with the validation, since you're using Rails:

def full_address
return "" unless self.address1 && self.city && self.address1.present? && self.city.present?
[self.address1, self.address2, self.address3,
self.city, self.state, self.zipcode].reject!(&:present?).join(', ')
end

How to efficiently check if a value passed to a view is nil or empty

Use @cart.blank? to check whether it is nil or empty. The blank? method is a rails extension.

Check if Object is nil and needed attribute is nil or empty

What about this?

data = response.try(:[], 'data')
raise Exception, "Response is not valid" if data.nil? || data.empty?

As @ksol correctly mentions in the comments, try helper comes from ActiveSupport. But it is not difficult at all to re-implement.

class Object
def try method, *args
if respond_to? method
send method, *args
else
nil
end
end
end

class Foo
def hello name
"hello #{name}"
end
end

f = Foo.new
f.try(:bar) # => nil
f.try(:hello, 'world') # => "hello world"
nil.try(:wat) # => nil

Alternatives

Here's Object#andand if you don't want to drag along the entire activesupport and don't feel like writing code that's already written.

data = response.andand['data']
raise Exception, "Response is not valid" if data.nil? || data.empty?

Replace Nil Values before_save Rails

My advice would be to leave them as nil in the database. If you need to display "Not Listed" in your UI, then do that when you display the data. This provides a number of benefits:

  • You can easily change "Not Listed" to something else down the road.
  • You can translate it on the fly.
  • You won't ever confuse a blank "Not Listed" with a legitimate "Not Listed" entered by the user.

Having trouble setting an object to nil in ruby binary search tree

You cannot "set an object to nil". An object can never change its class, it either is an instance of Node or it is an instance of NilClass, it cannot at one point in time be an instance of Node and at another point in time be an instance of NilClass.

Likewise, an object cannot change its identity, object #4711 will always be object #4711, however, nil is a singleton, so there is only one nil and it has the same identity during the entire lifetime of the system.

What you can do is to bind the variable which references the object to nil. You are doing the opposite operation inside your insert method.

Ruby check if block is nil

It is unclear what you are asking, because a block itself can not be empty. Therefore, you might mean a few different things:

  1. A missing block. You can check if a block is given

    block_given?
  2. Block with empty body (aka {} or do end). This is not impossible, but requires some advanced voodoo ruby metaprogramming magic. Generally, if this is what you are looking for, either you are writing something very interesting or your approach is completely wrong.
  3. You want to check if the result of executing a block is "empty" without invoking it first. This is impossible. For example, consider the following block:

    { [nil, "", true].sample }

    Obviously, there is no way to know in advance.

  4. You are ok with calling the block. Then you can assign the result to a variable and make checks on it:

    def some_method
    evaluation_result = yield if block_given?
    if evaluation_result.nil? or evaluation_result == ""
    # do something if the block was not given or the result is nil/empty
    puts "Empty block? Seriously?"
    else
    # do something if the block was given and the result is non nil/empty
    puts evaluation_result
    end
    end

    Now when you invoke some_method:

    some_method { "something" } # => "something"
    some_method { 3 + 5 } # => 8
    some_method { nil } # => "Empty block? Seriously?"
    some_method { "" } # => "Empty block? Seriously?"
    some_method { } # => "Empty block? Seriously?"
    some_method # => "Empty block? Seriously?"

EDIT:
A workaround for case #3 might be to create two procs, one with what you want to do if the block is "empty" and one - if it is not, then pass them around to the endpoint where you will finally invoke the block. This might or might not be applicable depending on your exact situation.

EDIT2:
Another workaround can be to redefine the Proc#call method for your proc instances. However, this doesn't work for yield:

def secure(&block)
insecure_call = block.method(:call)
block.define_singleton_method(:call) do
insecure_call_result = insecure_call.call
if insecure_call_result.nil? or insecure_call_result == ""
"<b>Bummer! Empty block...</b>"
else
insecure_call_result
end
end
end

x = proc { }
y = proc { "" }
z = proc { nil }
a = proc { 3 + 5 }
b = proc { "something" }
u = proc { [nil, "", true].sample }
[x, y, z, a, b, u].each { |block| secure &block }

# some method that uses the block
def user(&block)
"What I got is #{block.call}!"
end

user &x # => "What I got is <b>Bummer! Empty block...</b>!"
user &y # => "What I got is <b>Bummer! Empty block...</b>!"
user &z # => "What I got is <b>Bummer! Empty block...</b>!"
user &a # => "What I got is 8!"
user &b # => "What I got is something!"
user &u # => Different each time

EDIT3: Another alternative, which is sort of cheating, is to wrap the given proc in another proc. This way, it will work for yield too.

def wrap(&block)
proc do
internal_proc_call_result = block.call
if internal_proc_call_result.nil? or internal_proc_call_result == ""
"<b>Bummer! Empty block...</b>"
else
internal_proc_call_result
end
end
end

Now using the result of wrap and will get you behavior similar to secure.



Related Topics



Leave a reply



Submit