2. Ext. to Class
• class_attribute
active_support/core_ext/class/
attribute.rb
class A
class_attribute :x
end
class B < A; end
class C < B; end
A.x = :a
B.x # => :a
C.x # => :a
B.x = :b
A.x # => :a
C.x # => :b
C.x = :c
A.x # => :a
B.x # => :b
one or more inheritable class attributes that can be overridden at any level down the hierarchy
3. Ext. to Class
• class_inheritable_accessor, _reader, _writer
active_support/core_ext/class/
inheritable_attributes.rb
module ActionController
class Base
# FIXME: REVISE/SIMPLIFY THIS COMMENT.
# The value of allow_forgery_protection is inherited,
# but its value in a particular class does not affect
# the value in the rest of the controllers hierarchy.
class_inheritable_accessor :allow_forgery_protection
end
end
: deprecated ➜ class_attribute instead
accessors for class-level data which is inherited but not shared with children
4. class C; end
C.subclasses # => []
class B < C; end
C.subclasses # => [B]
class A < B; end
C.subclasses # => [B]
class D < C; end
C.subclasses # => [B, D]
Ext. to Class
• subclasses
active_support/core_ext/class/
subclasses.rb
C
B
A
D
5. Ext. to Class
• descendants
active_support/core_ext/class/
subclasses.rb
class C; end
C.descendants # => []
class B < C; end
C.descendants # => [B]
class A < B; end
C.descendants # => [B, A]
class D < C; end
C.descendants # => [B, A, D]
C
B
A
D
6. Ext. to String
• Strings “(html) unsafe” by default since Rails3
"".html_safe? # => false
s = "".html_safe
s.html_safe? # => true
• html_safe no escaping
s = "<script>...</script>".html_safe
s.html_safe? # => true
s # => "<script>...</script>"
active_support/core_ext/string/
output_safety.rb
7. Ext. to String
• html_safe
active_support/core_ext/string/
output_safety.rb
<%= raw @cms.current_template %>
<%== @cms.current_template %>
def raw(stringish)
stringish.to_s.html_safe
end
8. Ext. to String
• squish, squish!
active_support/core_ext/string/
filters.rb
" n foonr t bar n".squish # => "foo bar"
9. Ext. to String
• truncate
active_support/core_ext/string/
filters.rb
"Oh dear! Oh dear! I shall be late!".truncate(20)
# => "Oh dear! Oh dear!..."
"Oh dear! Oh dear! I shall be
late!".truncate(20, :omission => '…')
# => "Oh dear! Oh …" …
"Oh dear! Oh dear! I shall be late!".truncate(18)
# => "Oh dear! Oh dea..."
"Oh dear! Oh dear! I shall be
late!".truncate(18, :separator => ' ')
# => "Oh dear! Oh..."
11. Ext. to String
• Output safety - Key-based interpolation
active_support/core_ext/string/
interpolation.rb
"Total is %<total>.02f" % {:total => 43.1}
# => Total is 43.10
"I say %{foo}" % {:foo => "wadus"}
# => "I say wadus"
"I say %{woo}" % {:foo => "wadus"}
# => KeyError
13. Ext. to String
• Output safety - strip_heredoc
active_support/core_ext/string/
strip.rb
if options[:usage]
puts <<-USAGE.strip_heredoc
This command does such and such.
Supported options are:
-h This message
...
USAGE
end