开发者

Replace output of true and false in a view with Rails

开发者 https://www.devze.com 2023-02-09 02:18 出处:网络
I’ve got a view which evaluates a database table with boolean values. Those fields contain, who thought of it, wether true or false.

I’ve got a view which evaluates a database table with boolean values. Those fields contain, who thought of it, wether true or false.

I’d like to replace this text 开发者_如何学编程with something like Yes and No. Or Ja und Nein. Doesn’t matter. Is there any Rails way to do that?


<%= @attribute ? 'Yes' : 'No' %>

A nice place to put this might be in the model, so

class Whatever < ActiveRecord::Base
  def something_yn
    attribute ? 'Yes' : 'No'
  end
end

And then in the view:

<%= @instance.something_yn %>


I made a version which preserves original functionality, while allowing customization in similar fashion to how DateTime.to_s(:style).

https://gist.github.com/pehrlich/4963672

class TrueClass
  def to_s(style = :boolean)
    case style
      when :word then 'yes'
      when :Word then 'Yes'
      when :number then '1'
      else 'true'
    end
  end
end

class FalseClass
  def to_s(style = :boolean)
    case style
      when :word then 'no'
      when :Word then 'No'
      when :number then '0'
      else 'false'
    end
  end
end

I put this in lib and then include with this line in application.rb:

require "./lib/boolean.rb"
0

精彩评论

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

关注公众号