0

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

ohho
  • 50,879
  • 75
  • 256
  • 383

4 Answers4

4

As requested.

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

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

x1a4
  • 19,417
  • 5
  • 40
  • 40
1

You could use:

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

though using exceptions is not very efficient.

Luis
  • 1,282
  • 1
  • 11
  • 25
0

Does

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

work for you?

Aidan Cully
  • 5,457
  • 24
  • 27
  • sorry, return should be `reocrd.value`, not record – ohho Jun 04 '10 at 02:42
  • 1
    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 Jun 04 '10 at 02:44
  • @x1a4, can you put it in an answer? such that I can credit you – ohho Jun 04 '10 at 02:52
0

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,204
  • 28
  • 33