开发者

Can we change the way Rails writes HTML IDs and such?

开发者 https://www.devze.com 2022-12-21 03:26 出处:网络
I just started checking out Wordpress\' CSS Architecture to study a system that\'s established and pretty powerful to learn better HTML habits.I\'ve noticed th开发者_JAVA百科ey use all hyphens - (post

I just started checking out Wordpress' CSS Architecture to study a system that's established and pretty powerful to learn better HTML habits. I've noticed th开发者_JAVA百科ey use all hyphens - (post-554 for example), while Rails uses underscores _ (post_554 for example). I'm wondering if there's some setting to customize this in Rails, something like ActionView::Template.word_boundary = "-".

Is there? Not that it really matters, just trying to learn why people do things the way they do.

:)


You can't change se separator. It is hard-coded into Rails. For example, post_554 is generated by the dom_id helper, which internally relies on the RecordIdentifier class.

Here's the definition.

def dom_id(record, prefix = nil) 
  if record_id = record.id
    "#{dom_class(record, prefix)}#{JOIN}#{record_id}"
  else
    dom_class(record, prefix || NEW)
  end
end

The separator, the JOIN constant, is defined as freezed String so you can't change it.

module RecordIdentifier
  extend self

  JOIN = '_'.freeze
  NEW = 'new'.freeze

There are two ways to change it:

  1. Create your own helper (suggested)
  2. Overwrite the existing methods/helpers with your own implementations (not suggested)

There are also some technical restrictions that explain the reason behind this choice, mainly tied to the language behind Rails.

For instance, talking about symbols

:post_554   # valid symbol
:post-554   # invalid symbol
:"post-554" # valid symbol

Using - would probably require a less cleaner approach to Ruby.

Personally, I prefer using - rather than _ and I tend to avoid standard Rails helpers unless strictly required.

0

精彩评论

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