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"
精彩评论