From 0f847b95ebe2d80bfe67d4f182a4458f2091f322 Mon Sep 17 00:00:00 2001 From: Xavier Noria Date: Mon, 1 Mar 2010 06:07:31 +0100 Subject: AS guide: documents String#underscore --- .../source/active_support_core_extensions.textile | 79 ++++++++++++++++++++++ 1 file changed, 79 insertions(+) (limited to 'railties/guides/source') diff --git a/railties/guides/source/active_support_core_extensions.textile b/railties/guides/source/active_support_core_extensions.textile index c1a79189bd..51ef164d85 100644 --- a/railties/guides/source/active_support_core_extensions.textile +++ b/railties/guides/source/active_support_core_extensions.textile @@ -1299,6 +1299,85 @@ end NOTE: Defined in +active_support/core_ext/string/inflections.rb+. +h5. +camelize+ + +The method +camelize+ returns its receiver in camel case: + + +"product".camelize # => "Product" +"admin_user".camelize # => "AdminUser" + + +As a rule of thumb you can think of this method as the one that transforms paths into Ruby class or module names, where slashes separate namespaces: + + +"backoffice/session".camelize # => "Backoffice::Session" + + +For example, Action Pack uses this method to load the class that provides a certain session store: + + +# action_controller/metal/session_management.rb +def session_store=(store) + if store == :active_record_store + self.session_store = ActiveRecord::SessionStore + else + @@session_store = store.is_a?(Symbol) ? + ActionDispatch::Session.const_get(store.to_s.camelize) : + store + end +end + + ++camelize+ accepts an optional argument, it can be +:upper+ (default), or +:lower+. With the latter the first letter becomes lowercase: + + +"visual_effect".camelize(:lower) # => "visualEffect" + + +That may be handy to compute method names in a language that follows that convention, for example JavaScript. + ++camelize+ is aliased to +camelcase+. + +NOTE: Defined in +active_support/core_ext/string/inflections.rb+. + +h5. +underscore+ + +The method +underscore+ is the inverse of +camelize+, explained above: + + +"Product".underscore # => "product" +"AdminUser".underscore # => "admin_user" + + +Also converts "::" back to "/": + + +"Backoffice::Session".underscore # => "backoffice/session" + + +and understands strings that start with lowercase: + + +"visualEffect".underscore # => "visual_effect" + + ++underscore+ accepts no argument though. + +Rails class and module autoloading uses +underscore+ to infer the relative path without extension of a file that would define a given missing constant: + + +# active_support/dependencies.rb +def load_missing_constant(from_mod, const_name) + ... + qualified_name = qualified_name_for from_mod, const_name + path_suffix = qualified_name.underscore + ... +end + + +NOTE: Defined in +active_support/core_ext/string/inflections.rb+. + h3. Extensions to +Numeric+ h4. Bytes -- cgit v1.2.3