programing tip

레일은 현에 대해 '인간화'와 반대입니까?

itbloger 2020. 11. 17. 07:51
반응형

레일은 현에 대해 '인간화'와 반대입니까?


Rails는 humanize()Rails RDoc에서 다음과 같이 작동하는 문자열에 대한 메서드를 추가합니다 .

"employee_salary".humanize # => "Employee salary"
"author_id".humanize       # => "Author"

나는 다른 길로 가고 싶다. 모델의 속성에 쓰기 위해 '비인간 화'하려는 사용자의 "예쁜"입력이 있습니다.

"Employee salary"       # => employee_salary
"Some Title: Sub-title" # => some_title_sub_title

레일에 이에 대한 도움이 포함되어 있습니까?

최신 정보

그 동안 app / controllers / application_controller.rb에 다음을 추가했습니다.

class String
  def dehumanize
    self.downcase.squish.gsub( /\s/, '_' )
  end
end

그것을두기에 더 좋은 곳이 있습니까?

해결책

덕분에, 전략 중 에 대한 링크 . 거기에서 권장하는 솔루션을 구현했습니다. 내 config / initializers / infections.rb에서 마지막에 다음을 추가했습니다.

module ActiveSupport::Inflector
  # does the opposite of humanize ... mostly.
  # Basically does a space-substituting .underscore
  def dehumanize(the_string)
    result = the_string.to_s.dup
    result.downcase.gsub(/ +/,'_')
  end
end

class String
  def dehumanize
    ActiveSupport::Inflector.dehumanize(self)
  end
end

string.parameterize.underscore당신에게 동일한 결과를 줄 것이다

"Employee salary".parameterize.underscore       # => employee_salary
"Some Title: Sub-title".parameterize.underscore # => some_title_sub_title

또는 약간 더 간결하게 사용할 수도 있습니다 (@danielricecodes에게 감사드립니다).

  • 레일 <5 Employee salary".parameterize("_") # => employee_salary
  • 레일> 5 Employee salary".parameterize(separator: "_") # => employee_salary

Rail API에는 그러한 방법이없는 것 같습니다. 그러나 (일부) 솔루션을 제공하는이 블로그 게시물을 찾았습니다. http://rubyglasses.blogspot.com/2009/04/dehumanizing-rails.html


에서 http://as.rubyonrails.org/classes/ActiveSupport/CoreExtensions/String/Inflections.html 일부 싸게 치장하는 데 사용 방법과 해제 싸게 치장 문자열을 가지고있다.

참고 URL : https://stackoverflow.com/questions/2835786/does-rails-have-an-opposite-of-humanize-for-strings

반응형