Mitch
Mitch

Reputation: 1069

Passing a block to .try()

This question is about using the .try() method in rails 3 (& a bit about best practice in testing for nil also)

If I have a db object that may or may not be nil, and it has a field which is eg a delimited string, separated by commas and an optional semi-colon, and I want to see if this string contains a particular sub-string, then I might do this:

user_page = UserPage.find(id)
if user_page != nil
    result = user_page.pagelist.gsub('\;', ',').split(",").include?(sub)
end

So, eg user_page.pagelist == "item_a,item_b;item_c"

I want to re-write this using .try, but cannot find a way of applying the stuff after pagelist

So I have tried passing a block (from this link http://apidock.com/rails/Object/try)

user_page.try(:pagelist) {|t| t.gsub('\;', ',').split(",").include?(sub)} 

However, the block is simply ignored and the returned result is simply pagelist

I have tried other combinations of trying to apply the gsub etc part, but to no avail

How can I apply other methods to the method being 'tried'?

(I dont even know how to phrase the question in an intelligible way!)

Upvotes: 0

Views: 887

Answers (1)

Chris Heald
Chris Heald

Reputation: 62668

I think you're probably coming at this wrong - the quick solution should be to add a method to your model:

def formatted_pagelist
  (pagelist || "").split(/[;,]/)
end

Then you can use it where ever:

user_page.formatted_pagelist.include? sub

Strictly speaking, I'd say this goes into a decorator. If you're not using a decorator pattern in your app (look into draper!), then a model method should work fine.

Upvotes: 1

Related Questions