Beau Trepp
Beau Trepp

Reputation: 2770

Rails/Ruby one-liner unless zero/nil?

Is there a way to make this situation more compact in rails views?

Eg I have haml

= object.count unless object.count ==0

I sort of don't like that has I'm repeating the function there, I would much rather have something like

= object.count unless ==0

Eg if I had more complex statements

= object.relations.where(attribute: "something").count unless zero?

I could split that into two lines say

- cnt = object.relations.where(attribute: "something").count
= cnt unless cnt==0

But for each situation I would have multiple lines, and storing a variable to use once sucks.

EDIT: just to elaborate I want to check if the number is 0, and if so not display anything. It looks nicer in the view that way.

UPDATE:

One of the answers made come up with a solution along these lines

class Object
  def unless
    self unless yield(self)
  end
end

So I can call whatever object I have with a block eg. .unless{|c| c<1}

This lets me tack the conditionals on, and keeps it pretty clear what is going on :), bonus is as it's block driven I can use this on any object :P.

Thanks everyone :)

UPDATE EVEN MORE

Having |c| in the block sucked. So I looked up the api and changed it too

class Object
  def unless(&block)
    self unless instance_eval(&block)
  end
end

So now I can use .count.unless{zero?} to accomplish this :P. Or if I have a complicated condition I can add that in with |c| etc.

Upvotes: 1

Views: 7410

Answers (4)

john.jansen
john.jansen

Reputation: 41

i think the following is nice and clear, although i hate the variable "object", it would be much nicer if the name of the variable described the contents of the array (as plural)

= object.count unless object.empty?

Upvotes: 2

spas
spas

Reputation: 1934

Just create a view helper:

def display_count_or_nothing(array)
  array.count unless array.count == 0
end

In the view you can use it like this:

<%= display_count_or_nothing(array) %>

Upvotes: 3

Mischa
Mischa

Reputation: 43298

If this is only about count, you can monkey patch Enumerable:

module Enumerable
  def count_or_empty_string
    self.any? ? self.count : ''
  end
end

If object is an enumerable, you can do this:

= object.count_or_empty_string

This will return an "" if object.count == 0 else it will return an integer. So there is no need for unless or if in your HAML anymore.

Upvotes: 1

davidrac
davidrac

Reputation: 10738

If object is an array you can use object.empty? (or object.any? for the reverse case)

Upvotes: 3

Related Questions