开发者

Rails getter decoration

I have a view that is accessing attibutes from a model

.<%= @checklist.alt_escape_indicated %>

.<%= @checklist.sign_condition %>

Some of these are going to be booleans that I wanted displayed as 'Yes" or "No". I've written some code in my model class to do this:

def getter_decorator(attr)
  var = read_attribute(attr)
  if !!var == var
    boolean_as_string(var)
  else
    var
  end
end

def boolean_as_string(bool_type)
    if bool_type
      "Yes"
    else
      "No"
    end
end

So I can just do: .<%= @checklist.boolean_as_string(@checklist.sign_co开发者_JAVA百科ndition) %>

for attributes I know are boolean or getter_decorator on everything. My question is. Is there a way I can decorate all of my getters so this function is called when I do @checklist.sign_condition


I'd recommend making this a helper method since it's solely for presentation. That'll also make it easier to localize it in the future when your site takes off internationally...

def yn(val)
  val ? "Yes" : "No"
  # localized: I18n.t (val ? "Yes" : "No")
end

And then use it in your view:

<%= yn @checklist.sign_condition %>

However, if you REALLY wanted bools to automatically show up as Yes/No, you could do something like:

class TrueClass
  def to_s
    self ? "Yes" : "No"
  end
end

puts true #-> Yes

I wouldn't recommend that however ;)


Why not just override the getter or create a new one?

def sign_condition
  self.sign_condition == true ? "Yes" : "No"
end

If that causes a conflict (you'd have to test and see) just do the same thing with a slightly different name...

def sign_state
  self.sign_condition == true ? "Yes" : "No"
end


def getter_decorator(attr)
  var = read_attribute(attr)
  var == true ? "Yes" : var == false ? "No" : var
end


class Checklist
  %w(alt_escape_indicated sign_condition other_getters).each do |method|
    eval "def #{method}; super ? 'Yes' : 'No'; end"
  end
end
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜