views:

87

answers:

4

Any chance the 2nd and 3rd lines can be combined in an one-liner and hopefully save one valuable?

def self.date_format
  record = find_by_key('strftime')
  record ? record.value : "%Y-%b-%d'
end

the above function in a Config model try to fetch a database record by a key, return a default if not found in database.

Even better if can be written in named scope. Thanks

A: 

Does

value = find_by_key('strftime') || "%Y-%b-%d"

work for you?

Aidan Cully
sorry, return should be `reocrd.value`, not record
ohho
it's missing the `.value` call, but you can change it to `find_by_key('strftime').try(:value) || "%Y-%b-%d"` to keep it one line easily enough.
x1a4
@Horace: right, sorry, misread the code.
Aidan Cully
@Aidan, it was my fault. I edited the question.
ohho
@x1a4, can you put it in an answer? such that I can credit you
ohho
A: 

Do you need to assign a "value" variable at all? If not...

def self.date_format
  find_by_key('strftime') || "%Y-%b-%d"
end
Alison R.
+4  A: 

As requested.

Nobody yet has mentioned try, which is perfect for this situation:

value = find_by_key('strftime').try(:value) || "%Y-%b-%d"

x1a4
Though `try` is not defined in ruby so you'd have to add `require 'active-support'`
Jakub Hampl
question is tagged with `named-scope` and `activemodel` so was assumed.
x1a4
+1  A: 

You could use:

(find_by_key('strftime').value rescue nil) || "%Y-%b-%d"

though using exceptions is not very efficient.

Luis