"true" 및 "false" 문자열을 부울에 입력합니다.
저는 Rails 애플리케이션이 있고 jQuery를 사용하여 검색 보기를 백그라운드로 쿼리하고 있습니다.필드가 있습니다.q(검색어),start_date,end_date그리고.internal.그internal필드는 확인란이고 저는 사용하고 있습니다.is(:checked)쿼리되는 URL을 빌드하는 메서드:
$.getScript(document.URL + "?q=" + $("#search_q").val() + "&start_date=" + $("#search_start_date").val() + "&end_date=" + $("#search_end_date").val() + "&internal=" + $("#search_internal").is(':checked'));
이제 내 문제는.params[:internal]왜냐하면 "true" 또는 "false"를 포함하는 문자열이 있고 부울에 캐스트해야 하기 때문입니다.물론 이렇게 할 수 있습니다.
def to_boolean(str)
return true if str=="true"
return false if str=="false"
return nil
end
하지만 이 문제를 해결할 수 있는 더 루비적인 방법이 있을 거라고 생각해요!안 그래요?
내가 아는 한 부울런에게 줄을 거는 방법은 없지만, 만약 당신의 줄이 오직 다음과 같은 것으로만 구성되어 있다면요.'true'그리고.'false'방법을 다음과 같이 단축할 수 있습니다.
def to_boolean(str)
str == 'true'
end
ActiveRecord는 이 작업을 수행하는 깨끗한 방법을 제공합니다.
def is_true?(string)
ActiveRecord::ConnectionAdapters::Column::TRUE_VALUES.include?(string)
end
ActiveRecord::ConnectionAdapters::Column::TRUE_VALUESTrue 값의 모든 명백한 표현을 문자열로 사용합니다.
보안 공지사항
이 답변은 질문에 나온 답변이 아니라 아래에 나열된 다른 사용 사례에만 적합합니다.대부분 고정되어 있지만 사용자 입력을 YAML로 로드하여 발생하는 수많은 YAML 관련 보안 취약점이 있습니다.
문자열을 불스로 변환할 때 사용하는 트릭은 다음과 같습니다.
YAML.load(var) # -> true/false if it's one of the below
YAML boole는 상당한 양의 진실/거짓 문자열을 받아들입니다.
y|Y|yes|Yes|YES|n|N|no|No|NO
|true|True|TRUE|false|False|FALSE
|on|On|ON|off|Off|OFF
기타사용사례
다음과 같은 구성 코드가 있다고 가정합니다.
config.etc.something = ENV['ETC_SOMETHING']
그리고 명령행:
$ export ETC_SOMETHING=false
그 이후로ENVvars는 코드 안에 있는 문자열입니다.config.etc.something그의 가치는 문자열일 것입니다."false"그리고 그것은 잘못 평가될 것입니다.true. 하지만 이렇게 하면,
config.etc.something = YAML.load(ENV['ETC_SOMETHING'])
다 괜찮을 겁니다.이는 .yml 파일에서 구성을 로드할 때도 호환됩니다.
이 문제를 해결할 기본 제공 방법은 없습니다(액션 팩에는 이를 위한 도우미가 있을 수 있음).나는 이런 것을 충고하고 싶습니다.
def to_boolean(s)
s and !!s.match(/^(true|t|yes|y|1)$/i)
end
# or (as Pavling pointed out)
def to_boolean(s)
!!(s =~ /^(true|t|yes|y|1)$/i)
end
false/true 리터럴 대신 0과 non-0을 사용하는 것도 가능합니다.
def to_boolean(s)
!s.to_i.zero?
end
ActiveRecord::Type::Boolean.new.type_cast_from_userRails의 내부 매핑에 따라 이 작업을 수행합니다.ConnectionAdapters::Column::TRUE_VALUES그리고.ConnectionAdapters::Column::FALSE_VALUES:
[3] pry(main)> ActiveRecord::Type::Boolean.new.type_cast_from_user("true")
=> true
[4] pry(main)> ActiveRecord::Type::Boolean.new.type_cast_from_user("false")
=> false
[5] pry(main)> ActiveRecord::Type::Boolean.new.type_cast_from_user("T")
=> true
[6] pry(main)> ActiveRecord::Type::Boolean.new.type_cast_from_user("F")
=> false
[7] pry(main)> ActiveRecord::Type::Boolean.new.type_cast_from_user("yes")
DEPRECATION WARNING: You attempted to assign a value which is not explicitly `true` or `false` ("yes") to a boolean column. Currently this value casts to `false`. This will change to match Ruby's semantics, and will cast to `true` in Rails 5. If you would like to maintain the current behavior, you should explicitly handle the values you would like cast to `false`. (called from <main> at (pry):7)
=> false
[8] pry(main)> ActiveRecord::Type::Boolean.new.type_cast_from_user("no")
DEPRECATION WARNING: You attempted to assign a value which is not explicitly `true` or `false` ("no") to a boolean column. Currently this value casts to `false`. This will change to match Ruby's semantics, and will cast to `true` in Rails 5. If you would like to maintain the current behavior, you should explicitly handle the values you would like cast to `false`. (called from <main> at (pry):8)
=> false
그래서 당신은 당신만의 것을 만들 수 있었습니다.to_b(또는to_bool아니면to_boolean) 다음과 같은 이니셜라이저에서의 메서드:
class String
def to_b
ActiveRecord::Type::Boolean.new.type_cast_from_user(self)
end
end
레일 5에서 사용할 수 있습니다.ActiveRecord::Type::Boolean.new.cast(value)부울에 던져 넣는 겁니다
wannabe_bool gem을 사용하실 수 있습니다.https://github.com/prodis/wannabe_bool
이 보석은 A를 구현합니다.#to_bString, Integer, Symbol 및 NilClass 클래스에 대한 메서드입니다.
params[:internal].to_b
.str.to_s.downcase == 'true'완전성을 위하여그러면 어떤 것도 추락할 수 없습니다.str0 또는 0입니다.
그런 건 루비에 내장되어 있는 게 아닌 것 같아요.String 클래스를 다시 열고 to_bool 메서드를 추가할 수 있습니다.
class String
def to_bool
return true if self=="true"
return false if self=="false"
return nil
end
end
의 어느 할 수 있습니다.params[:internal].to_bool
버투스의 소스 코드를 보면 다음과 같은 작업을 할 수 있습니다.
def to_boolean(s)
map = Hash[%w[true yes 1].product([true]) + %w[false no 0].product([false])]
map[s.to_s.downcase]
end
만 하는 것을 할 수 .internal,이라면,면,의 url에를의합니다.params[:internal] 것입니다nil 됩니다.
저는 당신이 사용하는 특정 jQuery에 익숙하지 않지만, URL 문자열을 수동으로 만드는 것보다 원하는 것을 호출하는 더 깨끗한 방법이 있습니까?까를 본 이 있습니까?$get그리고.$ajax?
string 클래스에 to_boolean 메서드를 추가할 수 있습니다.그러면 true.to_boolean 또는 '1.to_boolean'to_boolean을 수행할 수 있습니다.
class String
def to_boolean
self == 'true' || self == '1'
end
end
아무도 이런 간단한 해결책을 올리지 않았다는 것이 놀랍습니다.그것은 당신의 문자열이 "진실" 또는 "거짓"이 되는 경우입니다.
def to_boolean(str)
eval(str)
end
언급URL : https://stackoverflow.com/questions/8119970/string-true-and-false-to-boolean
'programing' 카테고리의 다른 글
| TransactionSynchronizationManager.ActualTransactionActive()를 사용하는 것보다 Spring DB 트랜잭션이 활성 상태인지 탐지하는 더 나은 방법이 있습니까? (0) | 2023.10.01 |
|---|---|
| 여러 조건을 가진 XPath (0) | 2023.10.01 |
| c에서 여러 문자열을 연결하는 더 나은 방법? (0) | 2023.10.01 |
| 레벤쉬테인:MySQL + PHP (0) | 2023.10.01 |
| MySQL 스키마를 데이터와 함께 내보내는 방법은? (0) | 2023.10.01 |